Angular 4如何正确返回void observable

前端之家收集整理的这篇文章主要介绍了Angular 4如何正确返回void observable前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的Angular 4应用程序中,我有一个必须返回一个observable的方法,
这个方法有3个条件,第一个和第二个条件进行get调用,但是第三个条件不能做任何事情,在这种情况下我也必须返回一个observable,因为这个方法是.flatmap运算符的第一部分,所以要链接flatmap的第二部分我需要从第一部分开始观察.

我尝试:返回新的Observable< void>();但我有这个错误

ERROR TypeError: Cannot read property ‘subscribe’ of undefined

这是必须调用服务来加载数据的初始方法.

  1. loadModelData() {
  2. this.customerService.getModelDetail(this.code)
  3. .subscribe(response => {
  4. this.selected = response.body as Customer;
  5. });
  6. }
  7. }

这是必须链接2个调用的服务方法.

  1. getModelDetail(code) {
  2.  
  3. const params = new HttpParams().set('projection','withBalance');
  4.  
  5. return this.endPointUrlService.loadMaps(this.entityLink)
  6.  
  7. .flatMap((res) => {
  8. return this.http.get(this.endPointUrlService.cutLinks(
  9. this.endPointUrlService.map.get('customers')) + '/' + code,{observe: 'response',params: params})
  10. .map((response) => <any>response);
  11. })
  12. }

这是来自名为endPointUrlService的支持服务的方法,checkIfMapIsReady()是必须在第三种情况下返回void observable的方法

  1. loadMaps(entityLink: EntityLink[]): Observable<void> {
  2. console.log(entityLink);
  3.  
  4. for (const i in entityLink) {
  5. if (entityLink.hasOwnProperty(i)) {
  6. return this.checkIfMapIsReady(entityLink[i].name,entityLink[i].searchMap,entityLink[i].endPoints[0])
  7. }
  8. }
  9. }
  10.  
  11.  
  12. public checkIfMapIsReady(modelName: string,mapName: string,endPoints: string) {
  13.  
  14. if (this.map.get(modelName) === undefined) {
  15. console.log('endpoint url service All maps undefined ' + modelName);
  16. return this.getLinks(modelName,this.mapNames.get(mapName),false)
  17. } else {
  18. console.log('endpoint url service Populate only ' + mapName);
  19. if (this.mapNames.get(mapName).get(endPoints) === undefined) {
  20. return this.getLinks(modelName,true)
  21. } else {
  22. return new Observable<void>();
  23. }
  24. }
  25. }
也许Obse​​rvable.empty()是一个更好的选项,因为它不会发出任何值,下游运算符不会有它返回的问题!

注意,下游flatMap(res => …)和subscribe()不会触发.
既然你没有使用res,我认为这是理想的效果

为了更好地衡量,请返回类型Observable< any>.

我认为下面在逻辑上等同于发布的checkIfMapIsReady(),

  1. public checkIfMapIsReady(modelName: string,endPoints: string) {
  2.  
  3. const map = this.map.get(modelName);
  4. const name = this.mapNames.get(mapName);
  5. const endPointCheck = name ? name.get(endPoints) : null;
  6.  
  7. const links = !endPointCheck
  8. ? this.getLinks(modelName,name,!!map) // !! gives boolean true or false
  9. : Observable.empty();
  10.  
  11. const msg = !map
  12. ? 'endpoint url service All maps undefined ' + modelName
  13. : 'endpoint url service Populate only ' + mapName
  14. console.log(msg);
  15.  
  16. return links;
  17. );

猜你在找的Angularjs相关文章