📜  videoTitle$ Angular 2 - 两个兄弟组件之间的通信 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:49.957000             🧑  作者: Mango

代码示例1
Because you are working with Observers and Observables in your service, 
you don't need to communicate both components because you can directly
 connect the service with the component template. This should be the code:

Service:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject }    from 'rxjs/Subject';
import 'rxjs/add/operator/map';

@Injectable()
export class AppService {
  private apiURL = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails,status&maxResults=10&playlistId=PLSi28iDfECJPJYFA4wjlF5KUucFvc0qbQ&key=AIzaSyCuv_16onZRx3qHDStC-FUp__A6si-fStw&pretty=true";

  //Observable string sources
  private thisVideoTitle = new Subject();
  //Observable string streams
  videoTitle$ = this.thisVideoTitle.asObservable();
  constructor(private http:Http) { }

  getData() {
    return this.http.get(this.apiURL)
      .map((res:Response)=> res.json())
      .subscribe(nameTitle => this.thisVideoTitle.next(nameTitle))
  }
}

part ii
Then if you want to use this into your component template it should be something like: