Search code examples
angulartypescriptobservable

Type 'Subscription' is missing the following properties


IDE shows error when I write this code.

I have a component that calls service in ngOnInit to get the data. Service calls the other service to get some data and use it to get data then returns it.

component:

ngOnInit() {
    const token = "abc";
    this.service.getContactPersons(token).subscribe(
      persons => this.contactPersons = persons
    );

  }

service:

getContactPersons(token: string): Observable<ContactPerson[]> {
return this.tokenService.getParameters(token).pipe(
      switchMap((data: Params) => {
        return this.http.get<Properties>(
          this.baseUrl + `/abc/${data.param1}/properties/${data.param2}`
        );
      })
    ).subscribe((data: Properties) => data.contactPersons);
}

I've got this error: "Type 'Subscription' is missing the following properties from type 'Observable': _isScalar, source, operator, lift, and 6 more."


Solution

  • subscribe is not an rxjs equivalent of then. Specifically, with promises you can do somePromise.then(doSomething).then(doSomethingElse), but you can't someRxjsStream$.subscribe(doSomething).subscribe(doSomethingElse). If you want to transform the data stream, you should use one of several available rxjs operators, and in your case it's map:

    getContactPersons(token: string): Observable<ContactPerson[]> {
        return this.tokenService.getParameters(token).pipe(
            switchMap((data: Params) => this.http.get<Properties>(
                `${this.baseUrl}/abc/${data.param1}/properties/${data.param2}`)),
            map((data: Properties) => data.contactPersons));
    }