Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."

like image 341
genek Avatar asked Oct 08 '19 06:10

genek


1 Answers

subscribe is not a 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));
}
like image 105
mbojko Avatar answered Oct 09 '22 02:10

mbojko