2016-08-02 85 views
-1

我用兩個不同的組成部分,Angular2,如何從一個組件到另一個組件使用對象?

一個是sample.ts,另一個是testing.ts

export class TestComponent { 
save(){ 
    console.log('this is a testing file') 
    } 
} 

難道這possibe在sample.ts使用保存()?這是在testing.ts - >保存()??

如果可能的手段,有人plz幫助我...

+1

https://angular.io/docs/ts/latest/cookbook/component-communication .html –

+0

什麼是您的組件層次結構?哪個組件是父項,哪個是子項? – hendrix

+0

sample.ts是父母,testing.ts是孩子 – Ived

回答

0

我把這個功能在共享服務,並使其注射,並用它每一個地方。

@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(可能)並提供服務,並從任何子組件提供商列表中刪除它。

+0

如果我在我的save()方法中添加「Public」,它將顯示錯誤。 angular2-polyfills.js:390錯誤:SyntaxError:意外的令牌。(...):(:) – Ived

+0

我的錯誤,保存應該是一個功能,而不是一個類!:) – Milad

+0

是的,你是對的,我更新了它。我從一個組件到另一個組件達到了節省。但我無法獲得價值。好心地看到我的帖子plz ... – Ived

0

你可以讓你的方法public:public save() { ... },然後導入您TestComponent在SampleComponent,創建TestComponent的一個實例,並調用let tc = new TestComponent(); tc.save();

+0

我收到一個followng錯誤,angular2-polyfills.js:390錯誤:SyntaxError:Unexpected token。(...) – Ived

相關問題