angular - 为 Angular 4 中的所有组件注入(inject)服务作为单例

标签 angular typescript dependency-injection

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

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

这里有一些代码作为例子:

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说:

Dependencies are singletons within the scope of an injector.

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

提前致谢。

最佳答案

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

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

不要将它作为提供者添加到您的组件中。

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) { }

关于angular - 为 Angular 4 中的所有组件注入(inject)服务作为单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549930/

相关文章:

java - 多个实例中的 Dagger 2 单例

json - 期望字符串时,JSON.parse 位置 0 处的 JSON 中的 Angular Unexpected token c

dependency-injection - 对使用 IOC 容器、服务定位器和工厂感到困惑

angular - 如何在Angular 2.0中为Dart定义子路线

angular - Firebase : firebase. Promise<any> 与 Rxjs Promise<any> 的兼容性

angular - 禁用表单 typescript 中的所有控件

javascript - 如何在 typescript 中使用 "useContext"?

java - Dagger 2 和接口(interface)实现

javascript - 单击多个 div 但只显示一个类 (Angular2)?

angular-cli - 如何使用 Angular-Cli (v.1.0.0) 默认生成 Angular 2 项目