gpt4 book ai didi

angularjs - 在 Controller 中公开服务属性的正确方法是什么?

转载 作者:搜寻专家 更新时间:2023-10-30 21:12:35 25 4
gpt4 key购买 nike

想象一下,我有一个 Controller ctrlA。它有一个 serviceB 作为依赖项。该服务具有属性 propertyC。我将 Anguler 与 Typescript 结合使用。

在 UI 中,我想根据该属性的值显示和隐藏一些 html。

我可以:

  1. 将服务设为公共(public)变量并像这样访问它:<... ng-if="serviceB.propertyC">
  2. 在 Controller 中创建一个属性:

    public get exposedPropertyC(){    return this.serviceB.PropertyC;    }

并访问如下属性:<... ng-if="exposedPropertyC">

正确的做法是什么?

最佳答案

我不会说正确,但一致。它们都可以正常工作,但是,由于每个组件的职责之间缺乏一致性(它也可能存在测试问题),事情会开始出现问题。

你应该通过你的 Controller 公开一个属性,永远。它将保持其应有的责任。而且,通过这样做,您的服务也将履行其职责。

As it has been told by @LoremIpsum in the comments, another issue is "your HTML not reaching stuff that's too far".

这个问题有几个场景。考虑由 class MyController 声明的 Controller 。

直接访问属性

public exposedPropertyC: number;

constructor(private serviceB: ServiceB){
this.serviceB = serviceB;
this.exposedPropertyC = this.serviceB.PropertyC;
}

异步获取的属性

public exposedPropertyC: number;

constructor(private serviceB: ServiceB){
this.serviceB = serviceB;
this.serviceB.getPropertyC().then((propertyC) => {
this.exposedPropertyC = propertyC;
});
}

观察者模式

根据您的场景,有点矫枉过正,但观察者模式主要是一种最佳且奇特的解决方案。

下面的代码是这个模式的简单实现。但是,您可能会发现将此模式与 typescript 结合使用的功能更强大的库(但您明白了)。

Disclaimer. The observer pattern is my favorite one, even though it looks a bit of an overkill, it's much more flexible and compatible with future changes for optimizations and on how data are retrieved from the server, i.e., it brings lots of positive stuff for maintainability and also prevent future headaches because of a poor design ;{D

interface ObservableCallBack<T> {
(arg: T): void;
}

class Observable<T> {
public yielded: T;
public observers: ObservableCallBack<T>[];

public subscribe(observableCallBack: ObservableCallBack<T>): void {
this.observers.push(observableCallBack);
if(this.yielded !== null) observableCallBack(this.yielded);
}

public notify(arg: T): void {
this.yielded = arg;
this.observers.forEach((observer) => {
observer(arg);
});
}
}

class ServiceB {
public propertyC: Observable<number>;

constructor(private http: IHttpService) {
this.propertyC = new Observable<number>();

this.http.get('').then((res) => {
this.propertyC.notify(res.data);
});
}
}

class MyController {
public propertyC: number;

constructor(private serviceB: ServiceB) {
this.serviceB.propertyC.subscribe((propertyC) => this.propertyC = propertyC);
}
}

关于angularjs - 在 Controller 中公开服务属性的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com