サービスを介して2つのコンポーネント間でデータを渡そうとしています。私は他のコンポーネントからのサービスを介してデータをどのように消費できるのかよくわかりません。私は、2.DataからgetData()メソッドを介してデータを取得し、それをデータ変数に保存しています。メソッド内では印刷できますが、メソッド外では印刷できません。また、最初のコンポーネントに渡しました。私のコードで何が間違っていますか?サービス経由でデータを渡すAngular2(2つのコンポーネント)
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