【问题标题】:Inject service as singleton for all components in Angular 4为 Angular 4 中的所有组件注入服务作为单例
【发布时间】:2018-03-14 23:10:51
【问题描述】:

抱歉,如有重复,我已阅读相关帖子,但没有找到(或不理解)答案。

我有一个被许多组件使用的服务,我希望它成为所有组件(在所有应用程序中)的单例。 该服务必须发送一次请求并获取一次数据,然后在其他组件之间共享该数据。

下面是一些代码示例:

app.module.shared.ts

import { MyService } from '../services/myservice';

@NgModule({
    declarations: [
         //...
    ],
    imports: [
        //...
    ],
    providers: [
        MyService
    ]
})

myservice.ts

@Injectable()
export class MyService {
    shareData: string;

    constructor(private http: Http, @Inject('BASE_URL') private baseUrl: string) { }

    getSharedData(): Promise<string> {
        return new Promise<string>(resolve => {
            if (!this.shareData) {
                this.http.get(this.baseUrl + "api/sharedDara").subscribe(result => {
                    this.shareData = result.json() as string;                    
                    resolve(this.shareData);
                }, error =>  console.log(error));
            } else {
                resolve(this.shareData);
            }
        });
    }
}

example.component.ts(使用示例)

import { MyService } from '../services/myservice';

@Component({
    selector: 'example',
    templateUrl: './example.component.html',
    styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

    sharedData: string;

    public constructor(private myService: MyService,
        @Inject('BASE_URL') private baseUrl: string) { }

    ngOnInit() {
        this.myService.getSharedData().then(result => this.sharedData= result);
    }
}

Documentation 说:

依赖是注入器范围内的单例。

据我了解,每个组件都会创建自己的服务实例。这样对吗?以及如何为所有组件创建一个服务实例?

提前致谢。

【问题讨论】:

  • @Vega 在我的 /@NgModule 中我在提供程序中注册了服务(上面的代码),但是请求发送的次数与服务注入其他组件的次数一样多。这样我假设为每个组件创建服务实例
  • 这样是单例的。如果你想创建多个实例,你可以通过在组件级别而不是模块级别添加提供来做到这一点
  • @AniruddhaDas 但是服务的构造函数被调用了两次并且请求被发送了三次(但我真的希望它被发送一次)。没事吧?

标签: angular typescript dependency-injection


【解决方案1】:

要将服务用作具有多个组件的单例:

  • 导入
  • 将其添加到您的组件构造函数中

请勿将其作为 Provider 添加到您的组件中。

import { Service } from '../service';

@Component({
  selector: 'sample',
  templateUrl: '../sample.component.html',
  styleUrls: ['../sample.component.scss']
})
export class SampleComponent implements OnInit {

  constructor(private _service: Service) { }

要将服务用作您在其中使用它的每个组件中的新实例

  • 导入
  • 将其添加到组件构造函数中

请务必将其作为 Provider 添加到您的组件中

import { Service } from '../service';

@Component({
  selector: 'sample',
  templateUrl: '../sample.component.html',
  styleUrls: ['../sample.component.scss'],
  providers: [Service]
})
export class SampleComponent implements OnInit {

  constructor(private _service: Service) { }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-24
    • 2018-08-11
    • 2018-08-07
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多