我如何制作一个服务函数,它接受一个值并返回一个在Angular 2中可以观察到的值?
我的服务:-我如何制作一个服务函数,它接受一个值并返回一个在Angular 2中可以观察到的值?,angular,observable,Angular,Observable,我的服务:- @Injectable() export class MyService { doStuff(value){ //Do stuff and when done return new data return newData; } } @Injectable() export class MyService { myData:any = n
@Injectable()
export class MyService {
doStuff(value){
//Do stuff and when done return new data
return newData;
}
}
@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 implements OnInit {
constructor(private _myService: MyService){}
ngOnInit() {
this._myService.doStuff(value)
.subscribe((data) => {
console.log("new data: ", data);
})
}
}
export class MyComponent implement OnInit {
constructor(private _myService: MyService){}
ngOnInit() {
this._myService.doStuff(value);
this._myService.myDataAnnounce
.subscribe((data) => {
console.log("new data: ", data);
})
}
}
所以我的问题是,如何使doStuff()
函数返回一个可观察的值。我还想订阅上述函数,同时向其传递一个值。请问我该怎么做
我将一个变量设置为一个新的Subject()
(在我的服务中),然后调用所述变量的.next()
,并将值传回。唯一的问题是我必须调用我的doStuff()
函数,然后订阅变量,如下所示:-
我目前的服务:-
@Injectable()
export class MyService {
doStuff(value){
//Do stuff and when done return new data
return newData;
}
}
@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);
}
}
我想用我想传递的值打一个电话,然后订阅。提前感谢您提供的任何帮助。这很简单。正如@jornsharpe所说的,您只需要返回一些可观察到的。有时,如果我想在没有实际服务的情况下开始一些工作,我会使用相同的方法进行调试或作为开发的快速启动
@Injectable()
export class MyService {
doStuff(value) {
// When calling to real service is implemented
// you can just replace this with something like
// return this.http.get(...).map(r => r.json());
// If json response has the same structure as newData then
// your MyComponent will not even notice that something has changed.
return Observable.of(newData);
}
}
export class MyComponent implement OnInit {
constructor(private _myService: MyService){}
ngOnInit() {
this._myService.doStuff(value).subscribe((data) => {
console.log("new data: ", data);
});
}
}
返回可观察的(newData)
?这里的用例是什么?@jornsharpe我觉得可能是我想得太多了,在其他方法中陷得太深了。你说得对,我想:)明天我会再检查一遍。谢谢。是的,我想得太多了,而且非常直截了当。谢谢你们两位的帮助:)