无法读取未定义角度6的属性

时间:2019-03-25 21:44:28

标签: angular

我有一个非常简单的service.ts文件。我可以控制台记录responeDataSent对象。

  CallFunction() {
    this.http
      .post<{ someObject: any }>(
        'http://localhost:3000/apicall1',
        InputData
      )
      .subscribe(responseData => {
        this.responeDataSent = responseData;
        return this.responeDataSent;
      });
  }

如何在我的component.ts文件中阅读此response。请帮忙。

  private context: any;
  ngOnInit() {
    this.context = this.service.CallFunction();
    console.log(this.context);  // comes undefined.

  }

2 个答案:

答案 0 :(得分:1)

我想一种更好的方法来处理这种情况是您的服务函数应该首先返回一个Observable:

CallFunction(): Observable<any> {
  this.http.post<{ someObject: any }>(
    'http://localhost:3000/apicall1',
    InputData
  );
}

然后在component.ts中,您可以订阅并且代码可以处理响应:

ngOnInit() {
  this.service.CallFunction().subscribe(responseData => {
    console.log('response', responseData);
  });
}

进一步了解可观察对象:Observables

答案 1 :(得分:1)

这是我处理HttpClient请求的方式。 调用函数后返回http post / get。

CallFunction(InputData) {
        return this.http
          .post<{ someObject: any }>(
            'http://localhost:3000/apicall1',
            InputData
          );
      }

并使用调用后订阅功能。

private context: any;
  ngOnInit() {
this.service.CallFunction().subscribe(responseData => {
      this.context =  = responseData;
      // handle your data here
      console.log(this.context);  // comes undefined.
 } 
}