将对象推入角度为2的另一个组件数组中

时间:2017-11-09 05:02:26

标签: angular rxjs

    Like

    // My First Component
    @Component({
      selector: 'app-component1',
      templateUrl: './component1.html'
    })
    export class Component1 {
       books: any[] = ['Java'];
    }

    // My Second Component
    @Component({
      selector: 'app-component2',
      templateUrl: './component2.html'
    })
    export class Component2 {
     // Now I want to push 'Angular2' in books array from here. So, How can i do this and remember there is no any relationship of parent child component.
    }

我想将对象从Component2推送到Component1。

我已经尝试使用Observable。

在上述情况下,你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

您可以使用共享服务来管理它,将提供者:[myService]放在包含这两个组件的最高级别模块中,然后它成为单个对象。

@Injectable()
class myService{
books=[]
} 

// My First Component
@Component({
  selector: 'app-component1',
  templateUrl: './component1.html'
})
export class Component1 {
constructor(private _myService:myService){
   this._myService.boosk.push('Java')
}
}

// My Second Component
@Component({
  selector: 'app-component2',
  templateUrl: './component2.html'
})
export class Component2 {
constructor(private _myService:myService){
}
}