很抱歉,如果重复,我已阅读相关帖子,但未找到(或无法理解)答案。
我有许多组件使用的服务,我希望它成为所有组件的单例(在所有应用程序中)。 此服务必须发送请求并获取一次数据,然后在其他组件之间共享此数据。
以下是一些代码示例:
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);
}
}
依赖关系是注射器范围内的单例。
据我所知,每个组件都会创建自己的服务实例。这样对吗?以及如何为所有组件创建单个服务实例?
提前致谢。
答案 0 :(得分:6)
将服务用作包含多个组件的单例:
请勿将其作为提供商添加到您的组件中。
import { Service } from '../service';
@Component({
selector: 'sample',
templateUrl: '../sample.component.html',
styleUrls: ['../sample.component.scss']
})
export class SampleComponent implements OnInit {
constructor(private _service: Service) { }
要将服务用作中使用它的每个组件中的新实例:
将其作为提供商添加到您的组件
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) { }