角度服务-为什么选择行为主体而不是使用变量



我不明白为什么在组件本身中使用服务属性被认为是一个很大的禁忌。

我的意思是,我们需要一个行为主题的实际用例是什么?与仅使用变量相比,当按预期更改服务变量时,更改检测似乎按预期工作。

例如:

应用程序组件:

export class AppComponent {
constructor(public myService: ServiceNameService) {}
}

App.Component.html:

<li *ngFor="let item of myService.items">{{ item.Name }}</li>
<child-component></child-component>

MyService:

@Injectable({providedIn: 'root'})
export class ServiceNameService {
public items = [ { Name: "OLD NAME" }];
}

Child.Component.ts:

export class ChildComponent {
constructor(private myService: ServiceNameService) { }
onClick() {
this.myService.items[0].Name = "NEW NAME !";
}
}

上面的示例显示,从一个组件更改服务中的变量会在另一个组件中输出预期的更改为什么我们需要一个主题的复杂事物?我错过了什么?

第一个原因:有时在组件内部,您想要修改视图的数据。比如在每个项目中添加一个表示某个复选框值的字段。如果服务中只有价值,您将无法正确处理更新

第二个原因:通常Angular应用程序中的许多组件都标记为OnPush。你的应用程序的这些OnPush子树无法正确检测到来自服务的值的更改。但在受试者的帮助下,你将能够进行changeDetectorRef.markForCheck();

最新更新