【问题标题】:Angular: Declare global constant in serviceAngular:在服务中声明全局常量
【发布时间】:2020-06-27 23:46:56
【问题描述】:

我想调用一个调用 REST API 的服务,并使用返回的数据设置一个全局常量变量,然后可以在整个应用程序的组件中访问该变量。我不确定进行此操作的最佳方法。

【问题讨论】:

    标签: angular angular-services


    【解决方案1】:

    默认情况下,服务是单例(整个应用程序的一个实例),因此您存储在服务中的所有内容都可以共享给应用程序中的每个组件。

    【讨论】:

    • 不正确,除非它使用 {providedIn: 'root' },否则可以有多个副本
    • @un33k 在我的回答中添加了“默认”
    【解决方案2】:

    只需将您的服务设为根级别并将其注入其他服务和组件中,例如 ..

    @Injectable({providedIn: 'root'})
    export class MyService {
       data;
       constructor(private http: HttpClient) {
         this.http.get('some-url').subscribe(data => this.data = data);  
       }
    }
    

    现在任何组件都可以从根级服务中获取数据。

    @Component({
      selector: 'my-component',
      template: '<div>Hello</div>',
    })
    export class MyComponent {
       myData;
       constructor(private myService: MyService  {
         this.data = this.myService.data;
       }
    }
    

    以上代码仅作为示例。

    【讨论】:

    • 这非常适合我的情况。有没有办法让它在 API 调用需要一些时间时服务构造函数会等待它,这样当组件访问数据变量时它就不会未定义?
    • 我最终使用了 APP_INITIALIZER 依赖注入令牌,如此处所述stackoverflow.com/questions/50299147/…
    • 您也可以使用github.com/un33k/ngx-cfg 管理所有本地/远程配置文件
    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 2021-05-07
    • 2011-05-09
    • 2019-07-27
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多