加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 4如何正确返回void observable

发布时间:2020-12-17 07:27:54 所属栏目:安全 来源:网络整理
导读:在我的Angular 4应用程序中,我有一个必须返回一个observable的方法, 这个方法有3个条件,第一个和第二个条件进行get调用,但是第三个条件不能做任何事情,在这种情况下我也必须返回一个observable,因为这个方法是.flatmap运算符的第一部分,所以要链接flatmap的
在我的Angular 4应用程序中,我有一个必须返回一个observable的方法,
这个方法有3个条件,第一个和第二个条件进行get调用,但是第三个条件不能做任何事情,在这种情况下我也必须返回一个observable,因为这个方法是.flatmap运算符的第一部分,所以要链接flatmap的第二部分我需要从第一部分开始观察.

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

ERROR TypeError: Cannot read property ‘subscribe’ of undefined

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

loadModelData() {
      this.customerService.getModelDetail(this.code)
        .subscribe(response => {
          this.selected = response.body as Customer;
        });
    }
  }

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

getModelDetail(code) {

    const params = new HttpParams().set('projection','withBalance');

    return this.endPointUrlService.loadMaps(this.entityLink)

      .flatMap((res) => {
        return this.http.get(this.endPointUrlService.cutLinks(
          this.endPointUrlService.map.get('customers')) + '/' + code,{observe: 'response',params: params})
          .map((response) => <any>response);
      })
  }

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

loadMaps(entityLink: EntityLink[]): Observable<void> {
    console.log(entityLink);

    for (const i in entityLink) {
      if (entityLink.hasOwnProperty(i)) {
      return this.checkIfMapIsReady(entityLink[i].name,entityLink[i].searchMap,entityLink[i].endPoints[0])
      }
    }
  }


  public checkIfMapIsReady(modelName: string,mapName: string,endPoints: string) {

    if (this.map.get(modelName) === undefined) {
      console.log('endpoint url service All maps undefined ' + modelName);
      return this.getLinks(modelName,this.mapNames.get(mapName),false)
    } else {
      console.log('endpoint url service Populate only ' + mapName);
      if (this.mapNames.get(mapName).get(endPoints) === undefined) {
      return  this.getLinks(modelName,true)
      } else {
        return new Observable<void>();
      }
    }
  }
也许Obse??rvable.empty()是一个更好的选项,因为它不会发出任何值,下游运算符不会有它返回的问题!

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

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

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

public checkIfMapIsReady(modelName: string,endPoints: string) {

  const map = this.map.get(modelName);
  const name = this.mapNames.get(mapName);
  const endPointCheck = name ? name.get(endPoints) : null;

  const links = !endPointCheck 
    ? this.getLinks(modelName,name,!!map)     // !! gives boolean true or false
    : Observable.empty();

  const msg = !map 
    ? 'endpoint url service All maps undefined ' + modelName
    : 'endpoint url service Populate only ' + mapName
  console.log(msg);    

  return links;
);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读