【发布时间】:2017-02-17 09:27:06
【问题描述】:
我有这样的父组件:
import { Component } from '@angular/core';
import { UrlService } from '../../services/url.service';
@Component({
selector: 'wrapPost',
templateUrl: './app/html/wrapPost.component.html',
})
export class WrapPost {
dataPost: any;
url: string;
constructor(private urlService: UrlService) {}
ngOnInit(){
let url = window.location.pathname;
this.urlService.getData(url)
.then(res => this.dataPost = res);
}
}
从服务器获取日期并返回 this.dataPost。 效果很好。
父templateUrl: './app/html/wrapPost.component.html'的这个html
<div class="noteCommonAlign">
<navigation></navigation>
<posts [dataPost]="dataPost"></posts>
<loading class="noteCommonAlign"></loading>
<pagination [dataPost]="dataPost"></pagination>
</div>
进一步的组件分页(子)
import { Component, Input, SimpleChanges } from '@angular/core';
@Component({
selector: 'pagination',
templateUrl: './app/html/pagination.component.html',
styleUrls: ['app/css/pagination.component.css']
})
export class Pagination {
pagCurrent: number;
@Input() dataPost: any;
constructor(){
}
ngOnChanges(changes: SimpleChanges){
try{
console.log(this.dataPost);
} catch(err) {
console.log(err);
}
}
}
我无法异步获取 this.dataPost。当我在没有 ngOnChanges console.log(this.dataPost) 的情况下调用时,会发生错误。我稍微解决了这个问题。我使用了 ngOnChanges 但在控制台中显示了 2 条消息。一条消息有错误,另一条消息效果很好。
我如何理解它已经发生,因为 ngOnChanges 是生命周期,并且在 ngOnInit 之前以及每当一个或多个数据绑定输入属性更改时调用。 我不希望它被调用两次。
如何在具有@Input 的子组件中从服务器获取日期?
我很抱歉语法问题。我会很高兴任何解决方案。
【问题讨论】:
标签: angular