【问题标题】:How do I make a service function that takes a value and returns an observable in Angular 2?如何在 Angular 2 中创建一个接受一个值并返回一个 observable 的服务函数?
【发布时间】: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


【解决方案1】:

这很简单。正如@jonrsharpe 所说,您只需要返回一些可观察的。有时,如果我想在没有实际服务的情况下开始一些工作,我会使用相同的方法进行调试或作为开发快速入门。

@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);
        });
    }
}

【讨论】:

  • 是的,我想多了,它非常简单。谢谢你们的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
相关资源
最近更新 更多