gpt4 book ai didi

angular - 如何将异步数据作为对象数组传递给子组件 - angular 6

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:28 25 4
gpt4 key购买 nike

我尝试将从我的服务器获取的一组对象传递给子组件,但我不明白为什么它不起作用。我在这里错过了什么?

父组件TS

  private movieListSub: Subscription;
private movies: UserMovie[] = [];

constructor( private movieService: UserMovieService) { }

ngOnInit() {
this.movieListSub = this.movieService.getUpdatedMovieList().subscribe(response => {
this.movies = response.userMovieList;
})
}

父组件 Html

 <ng-container *ngIf="movies">
<app-slider [data]="movies"></app-slider>
</ng-container>

子组件ts

export class SliderComponent implements OnInit {

@Input() data:UserMovie[];
private movies:UserMovie[];

ngAfterViewInit() {
console.log(this.data) // Empty Array
}

服务

   private userMovieList: UserMovie[] = [] 
private updatedUserMovieList = new Subject<{ userMovieList: UserMovie[]}>();


constructor (private http: HttpClient) {}

getAllMovies() {
return this.http.get<{movies:UserMovie[]}>(this.movieApiUrl)
.subscribe(response => {
this.userMovieList = response.movies,
this.updatedUserMovieList.next({userMovieList: this.userMovieList})
})
}

最佳答案

movies 是私有(private)的,因此子组件将无法访问,并且在 Prod Build 的情况下也会抛出错误。

试试这个:

movies$: Observable < UserMovie[] > ;

constructor(private movieService: UserMovieService) {}

ngOnInit() {
this.movies$ = this.movieService.getUpdatedMovieList();
}

模板:

<ng-container>
<app-slider [data]="(movies$ | async)?.userMovieList"></app-slider>
</ng-container>

这样,您就不必担心取消订阅 Observable。

此外,您将在 ngOnChanges 中获得 input 属性,而不是 ngAfterViewInit

export class SliderComponent implements OnChanges {

@Input() data: UserMovie[];
private movies: UserMovie[];

ngOnChanges() {
console.log(this.data);
}

关于angular - 如何将异步数据作为对象数组传递给子组件 - angular 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52375877/

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