json - Angular 2 : Is there a way of handling Observable (async) in the Component instead of of using the pipe in the template?

标签 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  -->

我的组件:

  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"

我的服务:

  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 = "dummy text data to save",有意义吗?

谢谢!

最佳答案

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

关于json - Angular 2 : Is there a way of handling Observable (async) in the Component instead of of using the pipe in the template?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940109/

相关文章:

json - 将 json 数组解码为 swift 中的对象

Java 中的 JSON 模式验证器和转换器

json - 将 JSON 映射到 PostgreSQL 中的列和行

node.js - 无法读取未定义的属性 'messages'

javascript - 应用程序路由优先于模块路由

javascript - 为什么这个简单的 rxjs 示例没有按预期运行

json - Swift:如何在异步 urlsession 函数中返回一个值?

javascript - polymer 。纸张子菜单触发器适用于纸张项目内的两个元素

rxjs - 为什么在 RxJS 中取消了 finalize?

angular - RxJS 行为主题和 Angular ngModel 与 ngFor 绑定(bind)