【问题标题】:Angular2 @Input and http.getAngular2 @Input 和 http.get
【发布时间】:2016-05-24 23:57:37
【问题描述】:

在将数据从一个组件传递到另一个组件时,我遗漏了一些东西。我使用 @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}} 似乎可行。

有什么想法吗?

谢谢

【问题讨论】:

    标签: input components angular angular-http


    【解决方案1】:

    有两种解决方案:

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

    Page {{config?.total}}
    

    这是来自 Angular 文档:

    Elvis 运算符 (?) 表示雇主字段是可选的,如果未定义,则应忽略表达式的其余部分。

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

    在这种情况下,您需要重写代码。

    【讨论】:

    • 请注意,async 管道不适用于对象:stackoverflow.com/a/34561532/215945
    • 非常感谢,第一个解决方案适合现在的需要!我找不到任何解决这个问题的方法...
    【解决方案2】:

    @Input() 修饰的变量在构造函数中不可用。您必须等到 Angular 解决绑定并稍后在 component's lifecycle 中访问它:

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

    【讨论】:

    • 我相信 OP 是在说 config 来自 HTTP 请求,所以它甚至可能在 ngOnInit() 中不可用。
    • 感谢您的回答。正如 Mark Rajcok 所说,它来自一个 HTTP 请求,我只是尝试了这个,但它不起作用
    • @Choppy 我认为它是在代码的其他地方定义的。在不知道您如何获得config 的情况下,无法向您提供如何解决此问题的更多详细信息。 Vlado 建议的解决方案应该适用于像您这样的简单用例。请记住,输入变量在构造函数中不可用 (;
    【解决方案3】:

    @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 中引发错误

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      相关资源
      最近更新 更多