2016-08-02 83 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

相关问题