2016-10-02 61 views
0

我想通過服務在兩個組件之間傳遞數據。我不知道如何通過另一個組件的服務來使用數據。我通過getData()方法從2.組件獲取數據並將其保存到數據變量中。我可以在方法中打印它,但不能在方法外部打印,也嘗試將它傳遞給第一個組件。我的代碼有什麼問題?Angular2通過服務傳遞數據(兩個組件)

1.組件文件

import {Component, OnInit} from '@angular/core'; 
import {PassProfileDataService} from '../common/PassProfileDataService'; 

@Component({ 

    selector: "profile", 
    templateUrl: `client/components/profile/profile.component.html` 

}) 

export class ProfileComponent implements OnInit{ 
public data; 

constructor(private _sharedService: PassProfileDataService){} 

ngOnInit() { 

this.data = this._sharedService.dataStringSource) 
    } 

} 

2.組件文件

import {Component} from '@angular/core'; 
import {PassProfileDataService} from '../common/PassProfileDataService'; 

@Component({ 

    selector: "search", 
    templateUrl: `client/components/search/search.component.html` 

}) 
export class ProfileComponent{ 

constructor(private _sharedService: PassProfileDataService){} 

this._sharedService.getData(data[0].values) 
ngOnInit() { 

    } 

} 

3. SharedService

import {Component, Injectable} from '@angular/core' 

@Injectable() 
export class PassProfileDataService { 

    public dataStringSource; 

    // Service message commands 
    getData(data: String) { 
    this.dataStringSource data; 

    }; 

} 

回答

0

作爲據我所知,當您的分析導致您將服務識別爲共享時,您應該在應用程序初始化中註冊該服務:這將允許您在Angular2應用程序中訪問相同的服務實例。實際上,在你app.ts文件...:

// other import statements... 
import { TheNameService } from "./services/the-name.service"; 
// other import statements... 

@Component({ 
    // other declarations... 
    directives: [TheNameService] 
    // other declarations... 
}) 

現在,隨着需要該服務的實例每個組件的import語句導入TheNameService。請記住,不要在組件的提供程序數組中插入TheNameService,否則您將在該組件中獲得服務的NEW實例!

這解決了你的一個問題。如果要共享的數據位於服務的公共屬性中,則設置。但是如果你正在使用一個與異步方法一起工作的複雜服務呢? EventEmitters提供幫助。

在TheNameService中聲明瞭EventEmitter類型的屬性,其中「type」是事件發出的數據的類型。即

public myevent$: EventEmitter<string>; 

在TheNameService的構造記得初始化這樣的EventEmitter:

this.myEvent$ = new EventEmitter(); 

每一次服務必須在應用程序共享數據:

this.myEvent$.emit("This is the emitted text!"); 

記住認購組件到事件...這是一個很好的做法,將訂閱存儲在組件的屬性中,因爲當組件是dest時,我們需要取消訂閱已偵聽的事件royed。首先聲明你的組件上一個新的私有財產:

private _myEventSubscription: any; // not sure about what kind of data type is returned here... 

訂閱的ngOnInit方法的服務事件:

ngOnInit() { 
    this._myEventSubscription = this._theNameService.myEvent$.subscribe((emittedString: string) => { 
     console.log(emittedString); // will log "This is the emitted text!" in the console 
    }); 
} 

其中this._theNameService是TheNameService與依賴注入的構造函數注入(如下...)

constructor(private _theNameService: TheNameService) { } 

最後要做的,註銷認購成分破壞的情況下:

ngOnDestroy() { 
    this._myEventSubscription.unsubscribe(); 
} 
+0

我試過了,但出了點問題。也許你可以用我上面的代碼解釋它? – Tony

0

做,而你切換部件保存數據的服務。下面是一個例子。

import { Injectable } from '@angular/core'; 

@Injectable() 
export class TransfereService { 

    constructor(
    private router:Router, 
    private companyServiceService:CompanyServiceService 
) { } 

    private data; 

    setData(data){ 
    this.data = data; 
    } 

    getData(){ 
    let temp = this.data; 
    this.clearData(); 
    return temp; 
    } 

    clearData(){ 
    this.data = undefined; 
    } 

} 

現在考慮2個組件發送者和接收者。

發件人代碼:此代碼將數據設置爲服務並導航到接收者。

import { Router } from '@angular/router'; 
import { TransfereService } from './services/transfer.service'; 

export class SenderComponent implements OnInit {   
    constructor(
    private transfereService:TransfereService, 
    private router:Router) {} 

    somefunction(data){ 
    this.transfereService.setData(data); 
    this.router.navigateByUrl('/reciever');//as per router 
} 
} 

Reciever的代碼:此代碼從服務中提取數據並清除數據,以及。

import { Router } from '@angular/router'; 
import { TransfereService } from './services/transfer.service'; 

export class RecieverComponent implements OnInit { 
data = this.transfereService.getData();  
constructor(
    private transfereService:TransfereService, 
    private router:Router) { 
     if(this.data){ 
     // do whatever needed 
     } 
     else{ 
     this.router.navigateByUrl('/sender'); 
     } 
    } 
}