我用兩個不同的組成部分,Angular2,如何從一個組件到另一個組件使用對象?
一個是sample.ts,另一個是testing.ts
export class TestComponent {
save(){
console.log('this is a testing file')
}
}
難道這possibe在sample.ts使用保存()?這是在testing.ts - >保存()??
如果可能的手段,有人plz幫助我...
我用兩個不同的組成部分,Angular2,如何從一個組件到另一個組件使用對象?
一個是sample.ts,另一個是testing.ts
export class TestComponent {
save(){
console.log('this is a testing file')
}
}
難道這possibe在sample.ts使用保存()?這是在testing.ts - >保存()??
如果可能的手段,有人plz幫助我...
我把這個功能在共享服務,並使其注射,並用它每一個地方。
@Injectable()
export class MyService{
public save(){
console.log('this is a testing file')
}
}
在你的組件:
constructor(private myService:MyService){
// use it however you want
myService.save();
}
如果你不想這樣做,你需要seperately僅導出功能:
export function save() {
console.log('this is a testing file')
}
編輯:
如果您希望保留所有組件的此服務狀態,則需要在頂級應用程序中提供該服務。
該服務將表現爲單例對象,並且所有子組件都將使用該對象,並且它將保存該狀態。
因此,去你的app.ts(可能)並提供服務,並從任何子組件提供商列表中刪除它。
你可以讓你的方法public:public save() { ... }
,然後導入您TestComponent在SampleComponent,創建TestComponent的一個實例,並調用let tc = new TestComponent(); tc.save();
我收到一個followng錯誤,angular2-polyfills.js:390錯誤:SyntaxError:Unexpected token。(...) – Ived
https://angular.io/docs/ts/latest/cookbook/component-communication .html –
什麼是您的組件層次結構?哪個組件是父項,哪個是子項? – hendrix
sample.ts是父母,testing.ts是孩子 – Ived