【发布时间】:2017-02-08 20:29:14
【问题描述】:
我的服务:-
@Injectable()
export class MyService {
doStuff(value){
//Do stuff and when done return new data
return newData;
}
}
我的组件:-
export class MyComponent implements OnInit {
constructor(private _myService: MyService){}
ngOnInit() {
this._myService.doStuff(value)
.subscribe((data) => {
console.log("new data: ", data);
})
}
}
所以我的问题是,如何让doStuff() 函数返回一个可观察的值。我还想订阅所述函数,同时将值传递给它。请问我该怎么做?
我让它工作,我将一个变量设置为一个新的Subject()(在我的服务中) - 然后我在所述变量上调用.next() 并将值传回。唯一的问题是我必须调用我的 doStuff() 函数,然后订阅变量,如下所示:-
我目前的服务:-
@Injectable()
export class MyService {
myData:any = new Subject<any>();
myDataAnnounce = this.myData.asObservable();
doStuff(value){
//Do stuff and when done return new data
this.myData.next(newData);
}
}
我当前的组件:-
export class MyComponent implement OnInit {
constructor(private _myService: MyService){}
ngOnInit() {
this._myService.doStuff(value);
this._myService.myDataAnnounce
.subscribe((data) => {
console.log("new data: ", data);
})
}
}
我想用我想要传递的值拨打一个电话,然后订阅。提前感谢您提供的任何帮助。
【问题讨论】:
-
return Observable.of(newData)? -
这里的用例是什么?
-
@jonrsharpe 我觉得我可能想多了,在其他方法中陷入了困境。你是对的,我认为:) 明天会仔细检查。谢谢。
标签: angular observable