简体   繁体   English

如何在角度6中将值作为可观察值返回

[英]How to return value as an observable in angular 6

I want to return value (any data) from service to component as an observable. 我想从服务到组件返回值(任何数据)作为可观察的。 After a couple of digging into observables found following solution: 经过对可观察对象的挖掘,发现以下解决方案:

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

Use of like so: 使用of像这样:

import { of } from 'rxjs';
...
return of(value);

which is equivalent to: 等效于:

return new Observable(obs => obs.next(value));

However, if you want to convert a given value (eg a Promise, an Observable-like, an Array, an iterable or an array-like object) you may want to use from : 不过,如果你想转换一个给定值(例如一个承诺,一个样观察的,一个数组,一个迭代或类似阵列的对象),你可能需要使用from

import { from } from 'rxjs';
...
return from(value);

Just return like below 像下面一样返回

import { Observable, of } from 'rxjs';

...

getData(value) : Observable<any> {
   // Simple way of sending value using of operator.
   return Observable.of(value);
}

Hope this help! 希望有帮助!

Here's what I do 这是我的工作

In your service file : 在您的服务文件中:

First I declare my observable this way 首先我以这种方式宣布我的可观察性

  myObs: BehaviorSubject<any> = new BehaviorSubject([]);

In a method you can set your datas into your obs : 在一种方法中,您可以将数据设置到obs中:

var myArray = [1,2,3,4,5];
this.myObs.next(myArray);

If you want your "controller" to subscribe this obs, in your service, just expose a getter : 如果您希望您的“控制器”订阅此obs,请在您的服务中公开getter:

public getMyObs(){
return this.myObs.asObservable()
}

And in your "controller" you can call it this way : 在“控制器”中,您可以这样称呼:

 ngOnInit() {

this.myService.getMyObs().subscribe(datas => {
    Do What you want with your datas
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM