我正在寻找一种从另一个可观察到的返回一个可观察的方法。我发现您可以使用pipe和map操作符来实现这一点,但它似乎不适合我。我做错什么了?
我使用角9.1.12和rxjs ~6.5.4。
示例: Service1
import { Observable, of } from 'rxjs';
export class Service1 {
test(): Observable<string> {
console.log(1);
return of('hey');
}
}Service2
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export class Service2 {
constructor(private service1: Service1) {}
test(): Observable<string> {
return this.service1.test().pipe(
map((value: string) => {
console.log(2);
return value;
})
);
}
}组件
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export class Component implements OnInit {
constructor(private service2: Service2) {}
test(): Observable<void> {
return this.service2.test().pipe(
map((value: string) => {
console.log(3);
}));
}
}
}控制台将只输出1。
发布于 2021-07-15 15:40:12
这是合理的,因为您从未订阅observables,因此它们从未实际发出或运行。
您应该像这样订阅组件。
this.test().subscribe();我创建了一个stackblitz来玩。
PS:请注意,当需要时,您也必须取消订阅。如果您不熟悉这些概念,我建议您阅读https://netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3文章。
发布于 2021-07-15 15:42:47
正如函数只在调用它们时在内部运行代码一样,Observables只在订阅它们时才运行它们的代码。
您看到1输出是因为您调用了this.service1.test()。
您看不到2或3,因为您从未订阅过这些Observables。
export class Component implements OnInit {
constructor(private service2: Service2) {}
test(): void {
this.service2.test().pipe(
map(_ => console.log(3))
).subscribe();
}
}https://stackoverflow.com/questions/68396687
复制相似问题