简体   繁体   English

Angular2 为什么使用异步管道

[英]Angular2 Why Async pipe

I understand the Async pipe works on observable and help us load thing async for data which will be coming later.我了解 Async 管道适用于 observable 并帮助我们为稍后将要出现的数据加载异步内容。

However I can work without using async too.但是我也可以在不使用异步的情况下工作。 Following is the code以下是代码

Component零件

export class XComponent{
     someProp: string;
     someList: string[];
     someFn(){
          this.someService.subscribe(
               data=>{
                    this.someProp = data.prop; 
                    this.someList = data.list;
               }
          );
     }
}

Template模板

.....

<label>Prop</label>
<span>{{someProp}}</span>
<label>List</label>
<span *ngFor="let item of someList">{{item}}</span>

Above code works for me without use of async and without any issue.上面的代码对我有用,不使用异步并且没有任何问题。 They why should I use async?他们为什么要使用异步? Is it because we don't need to declare a variable for data and we can use directly observable (We anyways needs to declare a observable instead of data though)?是不是因为我们不需要为 data 声明一个变量,我们可以直接使用 observable(我们无论如何都需要声明一个 observable 而不是 data)?

EDIT编辑

Following is the code taken from angular docs for async example以下是从角度文档中获取的异步示例代码

@Component({
  selector: 'async-observable-pipe',
  template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>'
})
export class AsyncObservablePipeComponent {
  time = new Observable<string>((observer: Subscriber<string>) => {
    setInterval(() => observer.next(new Date().toString()), 1000);
  });
}

Instead of that I can write取而代之的是,我可以写

@Component({
  selector: 'async-observable-pipe',
  template: '<div><code>observable|async</code>: Time: {{ time }}</div>'
})
export class AsyncObservablePipeComponent {
  time;
  constructor(){
    setInterval(() => time = new Date().toString(), 1000); 
  } 
}

To me second code looks clean too.对我来说,第二个代码看起来也很干净。 (Even cleaner) (更干净)

What : With AsyncPipe we can use promises and observables directly in our template, without having to store the result on an intermediate property or variable内容:使用AsyncPipe ,我们可以直接在模板中使用 Promise 和 Observable,而无需将结果存储在中间属性或变量中

Why :Normally to render result of promise or observable we have to do为什么:通常要呈现 promise 或 observable 的结果,我们必须这样做

  1. Wait for a callback.等待回调。

  2. Store the result of the callback is a variable.存储回调的结果是一个变量。

  3. Bind to that variable in the template.绑定到模板中的该变量。

async makes rendering data easier from promises and observables. async 使得从 promises 和 observables 渲染数据变得更容易。 Suppose if we use observables without async, we have to subscribe the data from observable and we need to unsubscribe that on ngdestroy hook to avoid memory leaks.but where as with async will take care of this automatically.假设如果我们在没有异步的情况下使用 observable,我们必须从 observable 订阅数据,并且我们需要在 ngdestroy 挂钩上取消订阅以避免内存泄漏。但是使用 async 会自动处理这个问题。

"The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes" “异步管道订阅 Observable 或 Promise 并返回它发出的最新值。当发出新值时,异步管道标记要检查更改的组件”

How如何

`@Component( 
{

selector: 'async-observ',

  template: `
 <div>
  <h5>Async demo</h5>
  <p>{{ observable | async }}</p> 
 </div>
})

class AsyncObservComponent {

    observable: Observable<number>;

    constructor() {

     this.observable = this.getObservable();

   }

  getObservable() {

    return Observable
      .interval(1000)
      .take(5)
      .map((v) => v*v)
   }

The main reason is because using an async pipe, your code will be much cleaner.主要原因是因为使用async管道,你的代码会更干净。

Imagine a case where the data returned consists of tens or hundreds of keys instead of two.想象一下这样一种情况,返回的数据由数十个或数百个键组成,而不是两个。 It would be too cumbersome to set all the inner variables.设置所有内部变量太麻烦了。

As an addition, according to the Angular docs , the AsyncPipe will only take the last value omitted by the observable (which is the perfect solution to show a value in the view).另外,根据Angular 文档AsyncPipe只会采用 observable 省略的最后一个值(这是在视图中显示值的完美解决方案)。 If you keep trace of the observable itself in the XComponent , you are then capable of getting all of the values, first values and do all sorts of data manipulation.如果您在XComponent中跟踪可观察对象本身,那么您就能够获取所有值、第一个值并进行各种数据操作。

EDIT: To support the new example you gave:编辑:为了支持你给出的新例子:

time = Observable.interval(1000).flatMap(() => new Date().toString());

You have to subscribe to observables to return their data.你必须订阅 observables 才能返回它们的数据。 Instead of subscribing manually, you can use the async pipe in your HTML file.您可以在 HTML 文件中使用异步管道,而不是手动订阅。 This will subscribe to the observable, return dynamic values, and unsubscribe the observable on component changes.这将订阅 observable,返回动态值,并在组件更改时取消订阅 observable。

@Component({
  selector: 'async-observable-pipe',
  template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>'
})
export class AsyncObservablePipeComponent {
  time = new Observable<string>((observer: Subscriber<string>) => {
    setInterval(() => observer.next(new Date().toString()), 1000);
  });
}

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

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