0

I have to subscribe twice on ngOnInit() in my component.ts but it seems that you can only subscribe once. The second subscription is ignored.

How can I solve that?

I tested it and changed the function and always the first subscription works the second is ignored..

It is just a dummy code, so do not wonder because of strange naming.

//service.service.ts
getUser(id: string){
   return this.http.get(this.url)
}

getOrder(){
   return this.http.get(this.anotherUrl)
}

//component.ts

constructor(private service: Service){}

public user: object;
public order: object;
public userID: string;
ngOnInit(){
    this.userID = this.route.snapshot.params['id'];
    this.service.getUser(this.userID).subscribe(user => { this.user = user });

    this.service.getOrder().subscribe(order => { this.order = order });
}

This would not work. Only the first subscription would work and the second would be ignored.

What can I do about it? How would it be right?

Thank you

Anna Marie
  • 91
  • 2
  • 11
  • You can subscribe to as many things as you want. How did you come to the conclusion that the second subscription is ignored? Those are unrelated subscriptions, there should be no problem – Tim Jun 11 '19 at 11:55
  • If I try to console log it nothing appears.. – Anna Marie Jun 11 '19 at 12:00
  • Well, do you see the http calls being made in the network tab? – Tim Jun 11 '19 at 12:03
  • yes, the second exit with a status 500 (internal server error) but the call itself is right and leads to the data – Anna Marie Jun 11 '19 at 12:08
  • Well then this appears to be a problem within your API :) – Tim Jun 11 '19 at 12:09
  • But if I exchange the function it works but the other not anymore :/. I need to define a variable ``` this.id = this.route.snapshot.params['id']; ``` before the first function. This would not be the problem, right? – Anna Marie Jun 11 '19 at 12:13
  • Since you have not posted much code, I cannot really help you. However, subscribe accepts error handling callback as 2nd argument. So you can log the error and see what went wrong. – Tim Jun 11 '19 at 12:16
  • I update the code above, one moment :). Not much of an update but I use the Id in this.url to get one single user, which works fine. – Anna Marie Jun 11 '19 at 12:17

1 Answers1

0

It is rather unclear what you are asking and your sample code does not really help.

Subscribe accepts error handling callback as 2nd argument. Since this appears to be an API problem, you can catch the error like this:

getData() {
    this.http.get(this.url).subscribe((result) => {
      this.data = result;
      console.log(this.data);
    },
    (errror: HttpErrorResponse) = > {
        // Error handling here
        console.log(errror);
    });
    }

Other than that, it is posisble to subscribe to multiple observables in ngOnInit.

Tim
  • 3,910
  • 8
  • 45
  • 80