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."
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With