我用两个不同的组成部分,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