user6882156
user6882156

Reputation:

How to initialize component data by calling a service through HttpClient

I'm seeing dozens of similar posts but none of the solutions worked for me. So please don't answer by sending me to read other posts 'cause I did it before posting here. I'm trying to initialize a component property by calling a service. here is the component code:

export class MyComponent implements OnInit {
  myData: number[];

  constructor(@Inject(MyService) private myService: MyService) {
}

ngOnInit() {
  this.myService.getMyData().subscribe(data => this.myData = data);
}

The service code is as follows:

@Injectable()
export class MyService implements OnInit {
  private numbers: Observable<number[]>;

  constructor(@Inject(HttpClient) private http: HttpClient) {}

  getMyData(): Observable<number[]> {
    return this.numbers;
  }

ngOnInit() {
 this.http.post<MyDataResponse> (this.url, new MyDataRequest(100))
   .subscribe(resp => this.numbers = 
   observableOf(resp.data));
}

At the runtime I get the following exception:

ERROR TypeError: Cannot read property 'subscribe' of undefined
at .../MyComponent.ngOnInit (...)
at checkAndUpdateDirectiveInline (core.js:18620)
at checkAndUpdateNodeInline (core.js:19884)
at checkAndUpdateNode (core.js:19846)
at debugCheckAndUpdateNode (core.js:20480)
at debugCheckDirectivesFn (core.js:20440)
at Object.eval [as updateDirectives] (...)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:20432)
at checkAndUpdateView (core.js:19828)
at callViewAction (core.js:20069

So, to resume, the component subscribes to an observable returned by a service by calling a rest endpoint. The rest endpoint works as expected and gets correctle called and returns the right response. The exception has probably to do with the asynchrounous type of the operation but I don't know how am I supposed to deal with that. Additionally, I don't need that the operation be asynchrounous but, as surprizing as it might be, I didn't find any way to perform synchrounous rest calls in angular. Could anyone please shad some more light on this ? Many thanks in advance. Nicolas

Upvotes: 0

Views: 412

Answers (1)

Daniel Pi&#241;eiro
Daniel Pi&#241;eiro

Reputation: 3149

Probably you are using the variable this.numbers in getMyData() before being the observable, therefore your error of undefined.

What you probably wanna do it's something like this:

ngOnInit() {
    this.numbers =  this.http.post<MyDataResponse> (this.url, new MyDataRequest(100));
}

Upvotes: 2

Related Questions