Ann*_*n_K 7 dependency-injection typescript angular
对不起,如果重复,我已阅读相关帖子,但没有找到(或不明白)答案.
我有一个由许多组件使用的服务,我希望它成为所有组件的单例(在所有应用程序中).此服务必须发送请求并获取一次数据,然后在其他组件之间共享此数据.
以下是一些代码示例:
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 } 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);
}
}
Run Code Online (Sandbox Code Playgroud)
文件说:
依赖关系是注入器范围内的单例.
据我所知,每个组件都创建了自己的服务实例.这样对吗?以及如何为所有组件创建单个服务实例?
提前致谢.
Jam*_*ngs 11
要将服务用作具有多个组件的单例:
请勿将其作为提供程序添加到组件中.
import { Service } from '../service';
@Component({
selector: 'sample',
templateUrl: '../sample.component.html',
styleUrls: ['../sample.component.scss']
})
export class SampleComponent implements OnInit {
constructor(private _service: Service) { }
Run Code Online (Sandbox Code Playgroud)
要将服务用作每个组件中的新实例,请将其用于:
请将其作为提供程序添加到组件中
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) { }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3652 次 |
| 最近记录: |