【问题标题】:Component interaction shared variable through all app Angular 2通过所有应用程序Angular 2的组件交互共享变量
【发布时间】:2017-06-07 14:32:38
【问题描述】:

我有 app.component.tsheader.component.tsusers.component.tsshared.service .ts 带有一个变量“options”。

app.component.html 我有类似的东西:

<app-header></app-header>
<router-outlet></router-outlet>

其中 app-header - 与 header.component.ts 相关,router-outlet - 与 users.component 相关.ts

ngOnInit()app.component.ts 中,我执行 ajax-request 以获取 "options" 并设置:

sharedService.options = "result of ajax"

然后我想在 headerusers 组件的 ngOnInit() 方法中使用 sharedService.options 变量.但有时我会遇到sharedService.options.property is undefined 的错误。

我该如何解决?

【问题讨论】:

标签: angular typescript


【解决方案1】:

你在你的服务和 ngOnInit 中使用了一个 observable, 您订阅了该服务。 这是通常的模式。

类似的东西。

在 service.ts 中

getAll():Observable<Object[]>{     
      return this.http.get(this.newsURL)
                .map(res=>res.json())
                .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }   

在 ngOnInit 中 你在构造函数中创建一个服务对象 &

this.myObject.getAll.subscribe(
 //logic goes here what u want to do for service return type.
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多