当没有结果返回时,如何防止Angular异步管道频繁进行服务器调用? [英] How can I prevent the Angular async pipe from making frequent server calls when no results come back?

查看:54
本文介绍了当没有结果返回时,如何防止Angular异步管道频繁进行服务器调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ngFor中使用 async 管道来观看Observable.Observable由命中我的服务器的服务创建,并且在加载时枚举ngFor循环时,该服务正确地调用了服务器.

I'm using the async pipe in an ngFor to watch an Observable. The Observable is created by a service that hits my server, and on load time when ngFor loop is enumerated, the service correctly makes a call to the server.

现在对于我不了解的部分:当任何结果返回时,一切都会按预期进行.但是,如果服务器响应说是404,并且没有可用于枚举的结果,则 async 管道会使服务继续触发请求,间隔为毫秒.这显然是不好的.这里的设计期望是什么?如何在使用异步管道时如何优雅地处理返回错误的Observable?

Now for the part I don't understand: when any results come back everything happens as expected. But if the server responds with say, a 404 and no results are available for enumeration, the async pipe causes the service to continue to fire requests, milliseconds apart. This is obviously no good. What's the design expectation here and how can I gracefully handle an Observable that returns an error while using an async pipe?

在组件模板中:

<li *ngFor="let person of persons | async">{{person.id}}</li>

在组件主体中:

get persons: Observable<Person[]> {
    return this.personService.list();
}

在服务中:

list(): Observable<Person[]> {
    if (this.persons && this.persons.length) {
        return Observable.from([this.persons]);
    } else {
        return this.http.get('/person')
            .map((response: Response) => response.json())
            .map((data: Person[]) => {
                this.persons = data;
                return data;
            })
            .catch((error: any) => {
                let errMsg = "some error..."
                return Observable.throw(errMsg);
            });
        }
    }
}

推荐答案

我遇到了一个非常相似的问题,这是由于Angular2更改检测的工作原理所致.有多种解决方案对我有用.

I had a very similar issue, and it was due to how Angular2 change detection works. There are multiple solutions that worked for me.

现在,当您调用 persons getter时,它总是返回 Observable new 实例(例如,不同的对象),因此Angular重新评估整个过程,并在下一个变更检测周期中再次执行,然后再次执行...因此,这是可以解决的方法:

Right now your when you call persons getter, it always returns a new instance of Observable (e.g. a different object), so Angular reevaluates the whole thing, and during the next change detection cycle, it does it once again, and then again, ... So, this is how it can be solved:

@Component({
    selector: 'my-comp',
    template: `{{ _persons | async }}`,
}) export class MyComponent implements OnInit {
    ngOnInit() {
        this._persons = this.personService.list();
    }
}

ChangeDetectionStrategy 更改为 OnPush

您可能想告诉Angular:我知道我在做什么,当发生一些更改时我会告诉你自己":

Change the ChangeDetectionStrategy to OnPush

You may want to tell Angular: "I know what I'm doing, I'll tell you myself when some change occurred":

import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'my-comp',
    template: `
      {{ persons | async }}
      <button (click)="reload">Reload</button>
    `,
}) export class MyComponent implements OnInit {
    constructor(private cd: ChangeDetectorRef) {}

    ngOnInit() {
        this.persons = this.personService.list();
    }

    reload() {
        this.persons = this.personService.list();
        // this tells Angular that a change occurred
        this.cd.markForCheck();
    }
}

这两种解决方案都对我有用,我决定采用第二种方法,因为它也是一种优化方法

Both of these solutions worked for me, and I decided to go with the second approach, since it's also an optimization

这篇关于当没有结果返回时,如何防止Angular异步管道频繁进行服务器调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆