抱歉,如果重复,我已经阅读了相关帖子,但没有找到(或不理解)答案。
我有一个由许多组件使用的服务,我希望它成为所有组件(贯穿所有应用程序)的单例。 此服务必须发送请求并获取一次数据,然后在其他组件之间共享此数据。
这里有一些代码作为例子:
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);
}
}
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/