gpt4 book ai didi

angular - 更新 Angular 5 中的子组件

转载 作者:行者123 更新时间:2023-12-02 21:10:15 24 4
gpt4 key购买 nike

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

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

它有一个名为 getTopicToFilter 的函数,该函数由另一个组件更新。这工作正常,并通过 @Output EventEmitter 为我提供了 TopicId

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

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>

最后是我的 child 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)
}
}
}
}

关于angular - 更新 Angular 5 中的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48105274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com