我想将值(任何数据)从服务返回到组件作为可观察对象。经过几次深入研究 observables 发现以下解决方案:
class AppService {
getData(value) {
// do we have any other best way to return value as an observable
return Observer.create((observer) => {
observer.next(value);
});
}
}
class AppComponent implements OnInit {
ngOnInit() {
this.dataService$ = this.appService.getData().subscribe((data) => {
// do some task with data
});
}
}
最佳答案
像下面一样返回
import { Observable, of } from 'rxjs';
...
getData(value) : Observable<any> {
// Simple way of sending value using of operator.
return Observable.of(value);
}
希望这有帮助!
关于angular - 如何以 Angular 6 的形式返回值作为 observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54999187/