[英]Angular 7 and up: service to inject two components not like singleton
[英]Inject service as singleton for all components in Angular 4
對不起,如果重復,我已閱讀相關帖子,但未找到(或未理解)答案。
我有一個由許多組件使用的服務,我希望它成為所有組件的單例(在所有應用程序中)。 此服務必須發送請求並獲取一次數據,然后在其他組件之間共享此數據。
以下是一些代碼示例:
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);
}
}
文件說:
依賴關系是注入器范圍內的單例。
據我所知,每個組件都創建了自己的服務實例。 這樣對嗎? 以及如何為所有組件創建單個服務實例?
提前致謝。
要將服務用作具有多個組件的單例:
請勿將其作為提供程序添加到組件中。
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) { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.