1

angular2 テンプレート内で関数呼び出しを使用します。関数自体は、http.get() を使用して http ネットワーク リクエストを実行し、実際には CSS スタイル オブジェクトである any[] の Observable を返します。

@Component({
    selector: "test-component",
    template: `<div *ngFor="let item of items" [ngStyle]="lookupStyle(item)"; }} </div>",
})
@Injectable()
export class TestComponent {

    @Input()
    items: Array<any>; 

    lookupStyle(params: any): Observable<any> {
        return this.http.get(/* ... */).map(/* ... */);
    }

    constructor(private http: Http) {}
}

しかし、上記のコードは無限ループを引き起こします! この関数lookupStyleは、angular2 の変更検出が行われるたびに評価されます。http.get()変更検出の実行をトリガーするため、http 要求が完了した後に関数がlookupStyle再評価されます - 無限ループがあります。

angularに関数をlookupStyle1回だけ評価するように指示できる解決策またはより良い方法はありますか? 今、私はビューモデルでいくつかの魔法を思いつくことができると思います.zip/.combineLatestが、これはやり過ぎのようで、多くの追加コードを生成します - それが私がより良い方法を探している理由です.

4

1 に答える 1

0

本当に一度だけ実行したい場合は、これでうまくいくはずです:

hasBeenRun: boolean = false;
@Component({
    selector: "test-component",
    template: `<div *ngFor="let item of items" [ngStyle]="lookupStyle(item)"; }} </div>",
})
@Injectable()
export class TestComponent {

    @Input()
        items: Array<any>; 

        lookupStyle(params: any): Observable<any> {
            if(!this.hasBeenRun){
                this.hasBeenRun = true;
                return this.http.get(/* ... */).map(/* ... */);
            }
        }
}
constructor(private http: Http) {}

hasBeenRun再度呼び出す場合は、他の場所で false に戻す必要があります。うまくいけば、これはあなたが探していたものですが、私ngOnInit()は非常に実行可能なソリューションであることにも賛成しています.

于 2016-08-15T17:47:12.860 に答える