Angular2:无法向其他组件发送数据。后端服务被称为两次

时间:2018-05-08 07:00:32

标签: angular angular-components angular-event-emitter

我有ngOnInit的要求,我从网址中提取查询参数,准备一个网址,使后端api调用类似http://localhost:8080/myapp/video0=5&video1=6的内容并发出收到的数据以供使用在其他组成部分。

现在,当我查看浏览器控制台和网络选项卡时,我看到两个对我的后端api的调用:一个没有参数,一个有参数。显然,带参数的一个可以获取所需的数据。此data在另一个组件中是必需的,以便进一步处理。

以下是ngOnInit在一个组件中的样子:

ngOnInit() {

this.activatedRoute.queryParams.subscribe((params: Params) => {
     this.video0 = params['video0'];
     this.video1 = params['video1'];
     this.video2 = params['video2'];
     this.video3 = params['video3'];

    this.sharedRequestPath = this.prepareSharedLinkRequestPath(this.video0,this.video1,this.video2,this.video3);  // creates a url for fetching data.

   this.getSharedVideosData(this.sharedRequestPath);  //this makes the backend call.

    this.addVideosEvent.emit(this.sharedVideos); //finally emitting the data populated in variable

 });
}

从后端获取数据的部分:getSharedVideoData

 getSharedVideosData(requestPath) {

  this.modelService.getVideos(requestPath).subscribe(
      data => {
      this.videoData = data;

            for (let j = 0; j < this.videoData.length; j++) {
                          this.sharedVideos[j] = this.videoData[j];
            }
      });  
   }
getVideos中的

modelService方法是:

getVideos(videoDataQuery): Observable < MyObj[] > {
    return this.http.get(videoDataQuery).map((response: Response) => {
        return <MyObj[]> response.json()
    }).catch(this.handleError);
}

最后,另一个组件上的发射器事件:

 <app-form (addVideosEvent)="addVideos($event)" ></app-form>

addVideos方法用于进一步处理包含alert语句的数据。当页面加载时,我看到两个警告语句,但都没有任何数据。

这很奇怪,因为浏览器网络选项卡向我显示响应,但我认为它没有正确发出。我这样做的方法是否正确?

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

只需在Component中订阅发出的数据并将其放在您想要的位置。

this.addVideosEvent.subscribe(yourEmittedData=>{
       console.log( 'emittedData' , yourEmittedData )
)

答案 1 :(得分:0)

  • 组件订阅的正确语法是=&gt;

    this.addVideosEvent.subscribe(yourEmittedData=>{
        console.log( 'emittedData' , yourEmittedData )
    

    }         )

  • 服务订阅的正确语法是=&gt;

     myFunction(callback:(data:any)=>void){
         this.addVideosEvent.subscribe((yourEmittedData:any)=>{
         console.log( 'emittedData' , yourEmittedData )
        callback(yourEmittedData);
    

    }             )         }