【发布时间】:2018-09-04 15:15:08
【问题描述】:
我有一个服务定义,它简单地执行以下操作:
@Injectable()
export class SettingService {
settingsForm : FormGroup;
constructor(private http:HttpClient, private httpErrorHandlerService : HttpErrorHandlerService) { }
getPreference() {
return this.http.get<Preference>('/api/admin/config');
}
这里是偏好模型的sn-p
export class Preference {
utilityName : string;
utilitySupportUrl : string
utilitySupportPhone : string;
utilitySupportEmail : string;
utilityPayBillUrl : string;
utilityUrl : string;
defaultLocale : string;
showTOC : Boolean;
showLastBilledDate : Boolean ;
notificationRangeInHours : String;
在我的组件中..
settingsForm: FormGroup;
public utilityPreference: Preference = new Preference();
constructor(private settingService: SettingService, private messageService: MessageService, private httpErrorHandler: HttpErrorHandlerService, private fb: FormBuilder, @Inject(APP_CONFIG) private config: IAppConfig) {
this.settingService.getPreference().subscribe((data) => {
console.log(data);
this.utilityPreference = data;
});
console.log("====Component's preference:"+ JSON.stringify(this.utilityPreference));
我的问题是我的组件无法获取订阅服务返回的 Observable 的副本。我把它设置为
this.utilityPreference = data;
换句话说,如果我做this.utilityPreference.utilityName,我看到的是NULL
有人可以在这里指出正确的方向吗?
【问题讨论】:
-
尝试在 ngOnInit 上订阅
-
尽量避免在构造函数中订阅,正如@Ricardo 所说,尝试 onInit,或者在它自己的方法中
标签: angular service components httpclient