簡體   English   中英

Angular2 @Input和http.get

[英]Angular2 @Input and http.get

將數據從一個組件傳遞到另一個組件時,我丟失了一些東西。 我使用@Input傳遞從http.get請求獲得的數據。 問題是,當請求尚未解決時,嘗試從傳遞的輸入訪問屬性時遇到錯誤。

//news.ts
import {Component} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Pagination} from './pagination';

@Component({
    selector: 'news',
    templateUrl: 'app/news.html',
    viewProviders: [HTTP_PROVIDERS],
    directives: [Pagination]
})
export class News {

    news = [];

    pagination: Pagination;

    constructor(http: Http) {
        http.get('http://test.com/data')
            .map(res => res.json())
            .subscribe(news => this.news = news);
    }
}

//pagination.ts
import {Component, Input} from 'angular2/core';

@Component({
    selector: 'pagination',
    templateUrl: 'app/pagination.html'
})
export class Pagination {
    // page: int = 1;

    @Input() config;

    constructor() {
        // this.page = this.config.number;
    }
}

//Pagination.html
Page {{config.total}}

config.total在加載時生成錯誤。 但是執行{{config}}似乎可以。

有任何想法嗎 ?

謝謝

有兩種解決方案:

您可以在pagination.html中使用Elvis運算符

Page {{config?.total}}

這來自Angular文檔:

Elvis運算符(?)表示“雇主”字段為可選字段,如果未定義,則應忽略表達式的其余部分。

第二種解決方案是使用異步管道: https : //angular.io/docs/ts/latest/api/common/AsyncPipe-class.html

在這種情況下,您將需要重寫代碼。

@Input()裝飾的變量在構造函數中不可用。 您必須等到Angular解決了綁定並在組件的生命周期中稍后再訪問它:

ngOnInit() {
    this.page = this.config.number;
}

@Vlado Tesanovic我剛剛嘗試了第二種解決方案,因為我可能需要處理構造函數中的數據。 我做了什么 :

//news.ts
    constructor(http: Http) {
        // http.get('http://lechiffonbleu.com:1337/news/test')
        //  .map(res => res.json())
        //  .subscribe(news => this.news = news);

        this.news = new Promise((resolve, reject) => {
            resolve = http.get('http://lechiffonbleu.com:1337/news/test')
                .map(res => res.json())
                .subscribe(news => this.news = news);

            console.log(this.news);
            console.log(resolve);
        });
    }

好吧,我無法弄清楚如何正確解決諾言,因此它不會在pagination.ts中的@input中引發錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM