【发布时间】:2019-03-07 14:26:59
【问题描述】:
我的 Angular 前端中有 2 项服务,一项用于 API 调用,一项用于共享两个不同组件的数据。所以第二个服务是使用API服务。
如果我只使用 API 服务并在我的组件中订阅我的 Observables,那么一切正常(在 xxx.component.html 中查看)。
因此,如果我在 app.module 中将这两个服务声明为提供程序,并将 API 服务注入到共享服务中,它将不再起作用。
使用调试器,我总是得到未在 settings.service.ts 中定义的变量“tmp”
我知道,我也可以对子组件使用 @Input 来做到这一点,但我认为使用服务对于解耦组件也是一种更好的方式。
有什么建议吗:)?
在我的代码下方:
api.service.ts
export class ApiService {
API_URL = 'https://localhost:44381/api/v1';
constructor(private httpClient: HttpClient) { }
/** GET settings from API*/
getSettings(): Observable<Setting[]> {
return this.httpClient.get<Setting[]>(this.API_URL + '/settings')
.pipe(
catchError(this.handleError('getSettings', [])));
}
}
settings.service.ts
export class SettingsService {
tmp: Setting[];
constructor(private apiService: ApiService) { }
getSettings(): void {
this.apiService.getSettings()
.subscribe(settings =>
this.tmp = settings);
}
getData(): Setting[] {
this.getSettings();
return this.tmp;
}
}
settings.component.ts
export class SettingsComponent implements OnInit {
settings: Setting[];
constructor(private settingService: SettingsService) { }
// Load Setting while starting
ngOnInit() {
// this.getSettings();
this.settings = this.settingService.getData();
}
// old code when using only API service which works..
/*getSettings(): void {
this.apiService.getSettings()
.subscribe(settings => this.settings = settings);
}*/
}
settings.component.hmtl
<div>
<table>
<tr>
<th>keyname</th>
<th>value</th>
<th>defaultValue</th>
<th align="right">text</th>
</tr>
<tr *ngFor="let s of settings">
<td>{{s.keyName}}</td>
<td>{{s.wert}}</td>
<td>{{s.defaultValue}}</td>
<td align="right">{{s.description}}</td>
</tr>
</table>
</div>
【问题讨论】:
标签: service dependency-injection angular6 angular-components