Type 'Subscription' is missing the following properties

19,505

Solution 1

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));
}

Solution 2

your function getContactPersons returns a subscriptions as it is now. just delete the .subscribe((data: Properties) => data.contactPersons); part of your function and it should do the trick.

Since your are going to return an Observable you should always try to just pass along the observable itself or perform Operations on it within a pipe() and only subscribe to it once, because multiple Subscription can get out of hand and result in memory leak and therefore performance loss for your users.

Share:
19,505
genek
Author by

genek

Updated on June 21, 2022

Comments

  • genek
    genek almost 2 years

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