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

问题描述 投票:3回答:3

我需要将一个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

特色组件是一个光滑的滑块

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的初学者,请帮帮我?

angular
3个回答
2
投票

我建议你创建qazxsw poi来管理你的Posts集合。

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

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); }); } } 必须是init的默认值,然后当消费者订阅它时,他将始终返回最后一次发射的值。

示例:BehaviorSuject不幸的是,由于您的服务器未通过https,因此您的网址发出了ajax请求错误。无论如何,这个在线样本是准备好检查完整代码。

__更新__

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


1
投票

您应该选择在组件中使用Online sample。 Angular中的服务是单例,这意味着它作为单个实例进行管理。因此,如果每个组件都访问该服务,他们将访问相同的共享数据。

这是一个Shared Service


1
投票

如果你有一个要共享的数据可以从所有组件访问,你可以使用ngrx Example进行状态管理,如果你寻找最好和最干净的解决方案,你可以只调用一次并将结果存储在商店中

store

您可以通过致电获取您需要的所有帖子列表

 you can dispatch your result inside the service

getPosts() {
  return this.http.get('http://grace-controls.com/mind-grid/mind_select.php')
 .map(res=>res.json()).subscribe((results) => {
    this.store.dispatch(new yourActions.GetPosts(result));
 })
}

返回一个observable,你可以订阅并获取你的数据

© www.soinside.com 2019 - 2024. All rights reserved.