Angular 2 - 两个兄弟组件之间的通信

时间:2018-01-03 12:36:23

标签: angular

我正在使用API​​来获取视频列表。我一直在尝试将当前(点击的)视频的详细信息从videoItemComponent打印到detailsComponent。两者都是同一父母的子女,共享共同的服务。当我单击列表中的图像时,它应该打开包含其详细信息的视频。我无法做的是在详情页面上打印点击视频的详细信息。以下是我的代码:

// VideoItemComponent:

import { Component, OnInit, Input} from '@angular/core';

@Component({
  selector: 'app-video-item',
  templateUrl: './video-item.component.html',
  styleUrls: ['./video-item.component.scss']
})
export class VideoItemComponent implements OnInit {
  @Input() item: any;
  vidTitle : string;
  vidDesc : any;
  vidDate : any;
  constructor() { }

  ngOnInit() {
  }

    clickMe(event){
      this.vidTitle = this.item.snippet.title;
      this.vidDesc = this.item.snippet.description;
      this.vidDate = this.item.snippet.publishedAt;
      console.log(this.vidTitle);
      console.log(this.vidDesc);
      console.log(this.vidDate);
      return this.vidTitle;
    }

}

// DetailsComponent:

import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AppService } from '../app.service';
import { Subscription }   from 'rxjs/Subscription';
@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.scss']
})
export class DetailsComponent implements OnInit {
  id : string;
  private player;
  private ytEvent;
  myData;
  name;
  title;
  subscription: Subscription;
  videoTitle: string;
  vidTitle: string;
  constructor(private appService : AppService, private route : ActivatedRoute) { 
    this.id = route.snapshot.params['videoId'];
    //this.title = route.snapshot.params['etag'];
    this.subscription = appService.videoTitle$.subscribe(
      videoTitle => {
        this.vidTitle = videoTitle;
        console.log('details');
        console.log(videoTitle);
        //this.id = imageId;
        //console.log (this.id);
        //return imageId;

    });
  }

  ngOnInit() {
    this.appService.getData().subscribe(data=> {
      console.log(data);
      this.myData = data;

    })
  //   this.name = this.route.params.subscribe(params => {
  //   this.title = params['title']; // (+) converts string 'id' to a number
  // });
  }
  onStateChange(event) {
    this.ytEvent = event.data;
  }
  savePlayer(player) {
    this.player = player;
  }

  playVideo() {
    this.player.playVideo();
  }

  pauseVideo() {
    this.player.pauseVideo();
  }

}

所以基本上我想在detailsComponent中的videoItemComponent中打印我从clickMe()方法获得的值。我很久以前就被困住了。

1 个答案:

答案 0 :(得分:2)

因为您在服务中使用Observers和Observable,所以您不需要与两个组件进行通信,因为您可以直接将服务与组件模板连接。这应该是代码:

<强>服务

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<string>();
  //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))
  }
}

然后,如果你想在组件模板中使用它,它应该是:

<li *ngFor="let title of videoTitle$ | async"></li>
相关问题