gpt4 book ai didi

Angular 4 将服务响应值传递给多个组件

转载 作者:太空狗 更新时间:2023-10-29 18:18:51 24 4
gpt4 key购买 nike

我需要将一个 http 响应值传递给多个组件。

我的主页组件 html 是

<app-featured></app-featured>
<app-filter></app-filter>
<app-business></app-business>

服务文件data-video.service

getPosts() {
return this.http.get('http://grace-controls.com/mind-grid/mind_select.php')
.map(res=>res.json())
}

featured.component.ts

特色组件是一个光滑的 slider

ngOnInit() {
this.dataServices.getPosts().subscribe((posts)=>{
this.slides.splice(0, 1);
for(let i=0; i<posts.length;i++) {
this.slides.push({img:posts[i].image_url});
}
})
}
slides = [{img:''}];

business.component.ts

    ngOnInit() {
//Here I have to request the same data service method or any common object access values here?
}

如何获取并打印业务组件中的值?。哪种方法最可取?我是 Angular 的初学者,请帮助我?

最佳答案

我建议您创建 BehaviorSubject 以在本地管理您的帖子集合。

首先要做的是像这样创建模型:

/**
* Strong type each item of your posts api.
*/
export class PostModel {
id: string;
title: string;
descreption: string;
image_url: string;
video_id: string;
country: string;
language: string;
company: string;
date: string;
clap: string;
views: string;
username: string;
}

然后你的服务看起来像这样:

@Injectable()
export class PostService {
// Should be private and expose by magic getter, present bellow.
private _posts$ : BehaviorSubject<PostModel[]>;

constructor(private http: HttpClient) {
// We init by empty array, this means if you subscribe before ajax answer, you will receive empty array, then be notify imediatly after request is process.
this._posts$ = new BehaviorSubject([]);
// Because this data is mandatory, we ask directly from constructor.
this.loadPost();
}

private loadPost() {
this
.http
.get('http://grace-controls.com/mind-grid/mind_select.php')
.pipe(map(res => (res as PostModel[]))) // We strong type as PostModel array
.subscribe(posts => this._posts$.next(posts)); // we push data on our internal Observable.
}
// Magic getter who return Observable of PostModel array.
get posts$() : Observable<PostModel[]> {
return this._posts$.asObservable();
}
// magic getter who return Observable of {img:string} array.
get slides$(): Observable<Array<{img:string}>> {
return this._posts$.pipe(map(posts => {
return posts.map(post => {
return {
img: post.image_url
}
});
}));
}
}

然后您可以在您的应用程序的任何地方使用您的数据,只需执行以下操作:

export class AppComponent implements OnInit{

constructor(private postService: PostService) { }

ngOnInit() {
this.postService.posts$.subscribe(posts => {
console.log(posts);
});
// OR
this.postService.slides$.subscribe(slides => {
console.log(slides);
});
}
}

详细信息:BehaviorSuject 必须使用默认值进行初始化,然后当消费者订阅它时,他将始终返回最后发出的值。

样本:Online sample 不幸的是,ajax 请求从您的 url 中抛出错误,因为您的服务器未通过 https。无论如何,此在线示例已准备好完整代码以供检查。

__ 更新 __

我已经更新我的示例,评论 HttpCall 并将其替换为虚拟数据。

关于Angular 4 将服务响应值传递给多个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50007904/

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