Angular 7共享服务未共享
创始人
2024-10-17 02:00:23
0

在Angular中,共享服务应该是可注入的,并且它的实例应该在整个应用程序中共享。如果你的共享服务不是共享的,可能有以下几个原因:

  1. 未在应用程序的根模块中提供共享服务: 确保你在应用程序的根模块(通常是app.module.ts)中提供了共享服务,并将其添加到providers数组中。例如:

    import { NgModule } from '@angular/core';
    import { SharedModule } from './shared/shared.module';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [SharedModule],
      providers: [SharedService], // 添加共享服务
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  2. 在每个组件中重新提供了共享服务: 如果你在每个组件中都在providers数组中提供了共享服务,那么每个组件都会有自己的服务实例,而不是共享的实例。确保只在根模块中提供共享服务,而不是在每个组件中提供。

  3. 使用了多个实例: 如果你在应用程序的不同地方使用了多个实例,那么这些实例之间不会共享数据。确保在整个应用程序中只使用一个共享服务实例。

这是一个示例共享服务的代码:

  1. 创建共享服务:

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class SharedService {
      sharedData: string;
    
      constructor() { }
    }
    
  2. 在应用程序的根模块中提供共享服务:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    import { SharedService } from './shared.service';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule],
      providers: [SharedService], // 提供共享服务
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  3. 在组件中使用共享服务:

    import { Component } from '@angular/core';
    import { SharedService } from './shared.service';
    
    @Component({
      selector: 'app-my-component',
      template: `
        
    {{ sharedService.sharedData }}
    ` }) export class MyComponent { constructor(public sharedService: SharedService) { } }

请注意,使用了providedIn: 'root'注解的共享服务会自动在应用程序的根模块中提供。如果你使用了新的Angular版本(如Angular 6+),你可以使用这种方式来提供共享服务,而不需要在根模块中显式提供。

相关内容

热门资讯

盘点几款!hhpoker德州牛... 盘点几款!hhpoker德州牛仔视频,hhpoker是正规的吗,力荐教程(有挂透明);实战中需综合运...
热点推荐!hhpoker德州真... 这是一款非常优秀的hhpoker德州真的假的 ia辅助检测软件,能够让你了解到hhpoker德州真的...
传递经验!wepoker辅助是... 传递经验!wepoker辅助是真的吗,wpk模拟器多开,力荐教程(有挂方法)1、玩家可以在wepok...
盘点一款!wepokerplu... 此外,数据分析德州(wepokerplus透视脚本免费)辅助神器app还具备辅助透视行为开挂功能,通...
最新通报!wejoker内置辅... 最新通报!wejoker内置辅助,红龙poker辅助,大神讲解(有挂软件)是由北京得wejoker内...
一分钟了解!wepoker私人... 一分钟了解!wepoker私人局外卦,wepoker安装教程,AI教程(有挂方法)这是由厦门游乐互动...
2分钟细说!佛手大菠萝有挂吗,... 2分钟细说!佛手大菠萝有挂吗,德普之星有辅助软件吗,安装教程(有挂透视)准备好在德普之星有辅助软件吗...
大家学习交流!wepoker有... 大家学习交流!wepoker有脚本吗,wepoker插件下载,2025新版教程(有挂辅助)准备好在w...
新手必备!werplan透视挂... 新手必备!werplan透视挂,wepoker透视是真的吗,wpk教程(有挂辅助);最新版2024是...
解密关于!hhpoker是真的... 解密关于!hhpoker是真的还是假的,wepoker的辅助器,实用技巧(有挂软件);hhpoker...