Angular2,如何将对象从一个组件用到另一个组件?

时间:2016-08-02 10:54:31

标签: angular angular2-directives

我正在使用两个不同的组件,

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

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

这可能是在sample.ts中使用save()吗?这是在testing.ts      - >保存()...

如果这可能意味着,任何人都可以帮助我...

2 个答案:

答案 0 :(得分: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();

  }

如果您不想这样做,您只需要单独导出该功能:

export function save() {

  console.log('this is a testing file')

}

编辑:

如果您希望将此服务的状态保留在所有组件上,则需要在顶级应用程序中提供该服务。

该服务将表现为单个对象,并且所有子组件都将使用它,并且它将保存状态。

所以转到你的app.ts(可能)并提供服务并从任何子组件提供者列表中删除它。

答案 1 :(得分:0)

您可以将您的方法公开:public save() { ... }然后在SampleComponent中导入TestComponent,创建TestComponent的实例并调用let tc = new TestComponent(); tc.save();