【问题标题】:calling a method inside a subscribe function is not waiting to get the result in angular 4在 subscribe 函数中调用方法不等待以角度 4 获得结果
【发布时间】:2017-10-11 12:04:26
【问题描述】:

我是 Angular 4 的新手。我正在使用 subscribe 方法获取结果集,在其中我需要调用另一个方法来操作第一个结果集。但在获得第二个结果集之前,该过程已经完成。

我在component.ts中的代码是

workItems: IGeneratedTasks[];
this._taskManagementService.getAllWorkItems()
  .subscribe(workItems => {
    this.workItems = [];
    if (workItems != null)
      workItems.forEach(result => {            

        this._taskManagementService.hasAttachment(result.id).subscribe(count => {
          console.log(count);
          if (count > 0)
            result.hasAttachment = true;  //hasAttachment is a property in IGeneratedTasks
        });         


        console.log(result.hasAttachment);


      });
    this.workItems = workItems;

  },
  error => this.errorMessage);

我的 service.ts 是

getAllWorkItems(): Observable<IGeneratedTasks[]> {       
    return this._http.get(this._workItemUrl)
        .map(res => res as IGeneratedTasks[] || [])
        .map(tasks => tasks.map(this.generatedTasksService.toGeneratedTasks))
        .catch(this.handleError);
}

 hasAttachment(id:Number): Observable<number> {       
    let myHeaders = new HttpHeaders();
    myHeaders.append('Content-Type', 'application/json');
    let myParams = new HttpParams();
    myParams = myParams.append('workItemId',id.toString());

    return this._http.get(this._hasAttachmentUrl,{ headers: myHeaders, params: myParams })
        .map(res => res)           
        .catch(this.handleError);
}

我是否以正确的方式调用这些方法?

建议后的小改动

this._taskManagementService.getAllWorkItems()

  .subscribe(workItems => {
    this.workItems = [];
    let newWI: IGeneratedTasks[] = [];
    if (workItems != null) {
      workItems.forEach(result => {
        result.isOverDue = result.duedate != null && result.duedate < (new Date()) && result.overallstatus != "4";
        workItems.forEach(result => {
          this._taskManagementService.hasAttachment(result.id).subscribe(count => {
            if (count > 0) {
              result.hasAttachment = true;
            }
            newWI.push(result);
          });

        })
      });

    }
 this.workItems = newWI;

    },
  error => this.errorMessage);

我有一个类似的电话,比如 hasAttachment

  this._taskManagementService.hasNote(result.id).subscribe(count => {
            if (count > 0) {
              result.hasNote = true;
            }                
          });

我在哪里添加这个,以便最终数据集包含 hasAttachment 和 hasNote。

【问题讨论】:

  • hasAttachment 仅在 subscribe 中可用(由于 Async)console.log 需要在订阅中,否则它会给出undefined。尝试在订阅中设置您的日志。 result.hasAttachment = true; console.log(result.hasAttachment); });
  • @Swoox hasAttachment 是我的数据集的一个属性,我正在设置该值。所以它也应该在外面显示订阅,不是吗?
  • 目前还不知道。
  • @Swoox 你是对的。将结果添加到新数组 newWI.push(result);给了我结果。还有一个疑问,如果我有类似的订阅,比如 hasAttachment(比如 hasNote)。我该如何一起做?
  • 您可以等待完成,然后再获取另一个。阅读stackoverflow.com/questions/34671715/….subscribe( function(response) { console.log("Success Response" + response)}, function(error) { console.log("Error happened" + error)}, function() { console.log("the subscription is completed")} );

标签: angular


【解决方案1】:

我解决了我的问题,代码是

this._taskManagementService.getAllWorkItems()

  .subscribe(workItems => {
    this.workItems = [];
    let newWI: IGeneratedTasks[] = [];
    if (workItems != null) {
      workItems.forEach(result => {
        result.isOverDue = result.duedate != null && result.duedate < (new Date()) && result.overallstatus != "4";
        workItems.forEach(result => {
          this._taskManagementService.hasAttachment(result.id).subscribe(count => {
            if (count > 0) {
              result.hasAttachment = true;
            }
          });
          this._taskManagementService.hasNote(result.id).subscribe(count => {
            if (count > 0) {
              result.hasNote = true;
            }                
            newWI.push(result);
          });
        })
      });
    }
    this.workItems = newWI;

  },
  error => this.errorMessage);

【讨论】:

    猜你喜欢
    • 2016-12-20
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多