Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a child component in Angular 5

I'm trying to update a child component in Angular 5, and cannot get it working.

My home component gets data via a service.

It has a function called getTopicToFilter which is updated by another component. This works fine and gives me the TopicId via an @Output EventEmitter.

My problem though is that articles aren't updating in a child component

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)
    }

}

Html for HomeComponent:

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

And finally my 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)
        }
    }
}

Update - this is my BlogService

public getPostsByTopic(topicId = ""): Observable<Post[]> {
   return this.http.get<Post[]>(this.baseUrl + '/getPostsByTopic?TopicId=${topicId}', { headers });
}
like image 288
Robbie Mills Avatar asked Sep 19 '25 08:09

Robbie Mills


1 Answers

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) 
    }
   }
 }
}
like image 73
Musab.BA Avatar answered Sep 22 '25 06:09

Musab.BA