我想通過服務在兩個組件之間傳遞數據。我不知道如何通過另一個組件的服務來使用數據。我通過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;
};
}
我試過了,但出了點問題。也許你可以用我上面的代碼解釋它? – Tony