角度 DI 服务 - 显示属性



我有一个服务(Foo(被依赖注入(constuctor(到许多组件中。此服务具有属性 (Foo.timeZone(。其中一个组件需要将此属性的值绑定到时区的模板列表 - 有效地允许用户更改时区并使其可供其他组件使用。将 foo.timeZone 属性绑定到模板可选列表的最佳方法是什么?

  1. 公共 DI 并直接绑定到属性? 构造函数(publicmyFoo: Foo( { }
  2. 组件上的公共属性,使私有 DI 属性和公共组件属性保持同步。
  3. 别的。。。

谢谢

如果您使用的是OnPush,那么最好使用Subject,因为使用公共服务的属性不会触发更改检测。

https://stackblitz.com/edit/angular-paxamw

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TimeZoneService {
private timeZone$ = new BehaviorSubject('America/Adak');
getTimeZone() {
return this.timeZone$.asObservable();
}
changeTimeZone(timeZone: string) {
this.timeZone$.next(timeZone)
}
}
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
import { TimeZoneService } from './time-zone.service';
import { Observable } from 'rxjs';

@Component({
selector: 'hello',
template: `
<p>{{timeZone$ | async}} <small>Use Subject</small></p>
`
,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent  {
timeZone$: Observable<string>;
constructor(public timeZoneService: TimeZoneService) {
this.timeZone$ = this.timeZoneService.getTimeZone()
}
}

还要创建一个访问器组件,然后使用模板引用变量。

import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
import { TimeZoneService } from './time-zone.service';
import { Observable } from 'rxjs';

@Component({
selector: 'time-zone-accessor',
template: ``,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TimeZoneAccessorComponent  {
timeZone$: Observable<string>;
constructor(public timeZoneService: TimeZoneService) {
this.timeZone$ = this.timeZoneService.getTimeZone()
}
}

使用模板引用变量。

<time-zone-accessor #timeZone></time-zone-accessor>
<p>{{timeZone.timeZone$ | async}}</p>

最新更新