Angular 2:有没有办法在Component中处理Observable(async)而不是在模板中使用管道?

时间:2016-10-09 04:44:47

标签: json angular rxjs observable

我目前正在使用Observable在Angular 2应用程序中获取一些数据,但是我只想在请求完成后发送数据以便在我的模板中显示。我知道有使用“myValue | async”但是为了这个应用程序的目的,我需要捕获变量中的值并将该变量(带有最终值)发送到我的模板。这是我的代码

     dataRetrieved() {
     this._privateVariable.getData();//this subscribes to an observable
     return true;//if the request was completed
 }

有办法吗?谢谢!

更新

感谢您的回复。以下是我所拥有的更好的样本:

JSON:

        { 
        "data": 
           {
             "id" : 1,
              "dataDescription": "dummy text data to save"
            } 
         } 

HTML模板:

<div>[ngmodel] = 'myVariable' </div> <!--myVariable should contain the value of "dataDescription" from my json object.  Here when I use the pipe/async instead of a variable I get an error  (_myPrivateVariable.myData | async)?.dataDescription  -->

MyComponent的:

  constructor (private _privateVariable: MyService){}
    ngOnInit() {


  this._privateVariable.getData();//this retrieves a json object, I want to be able to retrieve the value I need here instead that in the view using "| async"

为MyService:

  private _myData:BehaviorSubject<any> = new BehaviorSubject({});


 public myData: Observable<any> = this._myData.asObservable();


   getData (): Observable<any> {
    let obs = this._http.get(URL).cache();
    obs.subscribe( (response : Response) => {
        let responseData = response.json();            
        this._myData.next(responseData.data);

    });

最后,我需要的是设置myVariable =“虚拟文本数据保存”,有意义吗?

谢谢!

2 个答案:

答案 0 :(得分:6)

async pipe为您处理订阅。如果您想手动进行订阅,您可以随时订阅Observable并自行处理变量的更新。

See this plnkr for demonstration

相关代码:

import {Observable} from 'rxjs/Observable';

import "rxjs/add/observable/interval";

@Component({
  selector: 'my-app',
  template: `
    <div>
      <p>Counter with async: {{ counter | async }}</p>
      <p>Counter without async: {{ subscribedCounter }}</p>
    </div>
  `,
})
export class App {
  counter: Observable<number>;
  subscribedCounter: number;
  constructor() {
    this.counter = Observable.interval(1000);
    this.counter.subscribe(
      v => { this.subscribedCounter = v; }
    );
  }
}

答案 1 :(得分:0)

我的答案......

How can I create a variable in a service that gets its data from a promise yet is shared between two components?

...涵盖了您想要做的事情的基本示例(来自您的更新问题)。