对不起,如果重复,我已阅读相关帖子,但没有找到(或不明白)答案.
我有一个由许多组件使用的服务,我希望它成为所有组件的单例(在所有应用程序中).此服务必须发送请求并获取一次数据,然后在其他组件之间共享此数据.
以下是一些代码示例:
app.module.shared.ts
import { MyService } from '../services/myservice';
@NgModule({
declarations: [
//...
],
imports: [
//...
],
providers: [
MyService
]
})
Run Code Online (Sandbox Code Playgroud)
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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
example.component.ts(使用示例)
import { MyService …Run Code Online (Sandbox Code Playgroud)