繁体   English   中英

在Angular 5中更新子组件

[英]Updating a child component in Angular 5

我正在尝试在Angular 5中更新子组件,但无法使其正常工作。

我的家庭组件通过服务获取数据。

它具有一个名为getTopicToFilter的函数,该函数由另一个组件更新。 这工作得很好,给我的TopicId通过@Output EventEmitter

我的问题是,文章没有在子组件中更新

export class HomeComponent implements OnInit {
    loading = true;

    topics: Observable<Topic[]>;
    posts: Observable<Post[]>;

    public constructor(
        private blogService: BlogService
    ) { }


    ngOnInit() {
        this.posts = this.blogService.getPostsByTopic().share()
        // Note that the forkJoin gets other, unrelated data that I have removed from the question
        Observable.forkJoin([
            this.posts
        ]).subscribe(
            response => { },
            error => {
                console.log('An error occurred:', error);
            },
            () => {
                this.loading = false;
            });
    }

    getTopicToFilter(topicId) {
        // I've confirmed I get the right data back from my service based on the topicId
        this.posts = this.blogService.getPostsByTopic(topicId)
    }

}

适用于HomeComponent的HTML:

<app-posts [posts]="posts | async"></app-posts>

最后是我的孩子PostsComponent;

export class PostsComponent{
    @Input() posts: Post[];

    ngOnChanges(changes: SimpleChanges) {
        // only run when property "data" changed
        if (changes['posts']) {
            //  This is always outputting my original insights, not the filtered list
            console.log(this.posts)
        }
    }
}

更新-这是我的BlogService

public getPostsByTopic(topicId = ""): Observable<Post[]> {
   return this.http.get<Post[]>(this.baseUrl + '/getPostsByTopic?TopicId=${topicId}', { headers });
}
export class PostsComponent implements OnChanges {
@Input() posts: Post[];

ngOnChanges(changes: SimpleChanges) {
     for (let propName in changes) {
    // only run when property "data" changed
    if (propName === 'posts') {
         //  this line will update posts values 
         this.posts = changes[propName].currentValue

        console.log(this.posts) 
    }
   }
 }
}

尝试改变

export class PostComponent

export class PostComponent implements OnChanges

我认为最好的方法是在子组件上使用* ngIf

<child-component [posts]="data | async" *ngIf="dataIsReady" ></child-component>

在父组件中必须更新数据时

this.dataIsReady = false;
this.postService.getData().subscribe(
   (result: any) => {
     this.data = result;
     this.dataIsReady = true;
   }
);

* ng如果强制子组件重新渲染。 我希望你会发现这个有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM