Shidomaru NeveRage
Shidomaru NeveRage

Reputation: 276

How to share Angular services in promise chaining?

I'm working on Angular6 (typescript). I'm trying to chaining promise with the following code...

public start() {
    this.p1()
      .then(this.p2)
      .then(this.p3)
      .catch((err) => console.log(err));
  }

  public p1(): Promise<string> {
    return new Promise((resolve, reject) => {
      this.httpService.sendHello().subscribe(response => {
        resolve();
      });
    });
  }

  public p2(): Promise<string> {
    return new Promise((resolve, reject) => {
      this.httpService.sendHello().subscribe(response => {
        resolve();
      });
    });
  }

  public p3(): Promise<string> {
    return new Promise((resolve, reject) => {
      this.httpService.sendHello().subscribe(response => {
        resolve();
      });
    });
  }

But an error appears "Cannot read property 'httpService' of undefined".

How should I do to share angular6 services in promise chaining ?

Thanks for helping,

Upvotes: 0

Views: 222

Answers (4)

Yash Rami
Yash Rami

Reputation: 2317

You can use RxJS forkjoinhere is the example

ngOnInit() {
  chainCall().subscribe(resp=> {
   console.log(resp);
  })
}

chainCall(): Observable<any[]> {
const response1 =  this.httpService.sendHello();
const response2 = this.httpService.sendHello();

return forkJoin([response1, response2]);
}

Upvotes: 1

Silvermind
Silvermind

Reputation: 5944

Typescript does not bind this when you don't use the arrow function.

Instead of then(this.p2) you can write then(() => this.p2())

public start() {
    this.p1()
      .then(() => this.p2())
      .then(() => this.p3())
      .catch((err) => console.log(err));
  }

  public p1(): Promise<string> {
    return new Promise((resolve, reject) => {
      this.httpService.sendHello().subscribe(response => {
        resolve();
      });
    });
  }

  public p2(): Promise<string> {
    return new Promise((resolve, reject) => {
      this.httpService.sendHello().subscribe(response => {
        resolve();
      });
    });
  }

  public p3(): Promise<string> {
    return new Promise((resolve, reject) => {
      this.httpService.sendHello().subscribe(response => {
        resolve();
      });
    });
  }

Upvotes: 1

mbojko
mbojko

Reputation: 14679

It's the this context. Convert them to arrow functions:

  public p1 = (): Promise<string> => { //...

Upvotes: 1

Alex Cr
Alex Cr

Reputation: 441

You give it as an parameter to the function, like:

public start() {
    this.p1(this.httpService)
      .then(this.p2)
      .then(this.p3)
      .catch((err) => console.log(err));
  }

  public p1(httpService: HttpService): Promise<string> {
    return new Promise((resolve, reject) => {
      httpService.sendHello().subscribe(response => {
        resolve();
      });
    });
  }

Upvotes: 1

Related Questions