user2281858
user2281858

Reputation: 1997

cannot read property of undefined angular 6

I have a very simple service.ts file. I can console log the responeDataSent object.

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

In my component.ts file, how can I read this response. Please help.

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

  }

Upvotes: 0

Views: 71

Answers (2)

Hien Nguyen
Hien Nguyen

Reputation: 18975

This is my way to handle HttpClient request. Return http post/get after call in function.

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

And use subscribe after call function.

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

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

I guess a better way to deal with this scenario is that your service function should return an Observable first:

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

Then in component.ts you can subscribe and the code can handle the response:

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

Read further about Observables: Observables

Upvotes: 1

Related Questions