如何从服务器获取行为主体组合和错误方法?



我的服务如下所示:

@Injectable()
export class SettingService {
private settings = new BehaviorSubject<any[]>([]);
constructor(private http: HttpClient) {
this.loadSettings();
}
private loadSettings() {
this.http.get<any[]>('/api/settings')
.subscribe({
next: (settings) => this.settings.next(settings),
complete: () => this.settings.next,
error: (s) => this.settings.next(s)
});
}
getSettings() {
return this.settings.asObservable();
}
}

我正在我的组件中使用此服务:

@Component({
selector: 'app',
templateUrl: 'app.component.html'
})
export class AppComponent {
settings: any[];
constructor(settingsService: SettingService){
settingsService.getSettings().subscribe({
next: components => {
this.settings = settings;
},
error: (s) => {
console.log("error.")
},
complete: () => {
console.log("complated.")
}
});
}
}

但是错误或复合方法在组件中不起作用。只有下一个方法炒锅。

尽管你可以这样做

this.http.get<any[]>('/api/settings')
.subscribe({
next: (settings) => this.settings.next(settings),
complete: () => this.settings.complete(),
error: (s) => this.settings.error(s)
});

但实际上你应该直接调用 loadSettings 并用它分配属性

settingsService.loadSettings().subscribe(res=>this.settings=res)

我认为你的代码应该是这样的:

@Injectable()
export class SettingService {
private settings = new BehaviorSubject<any[]>([]);
constructor(private http: HttpClient) {
this.loadSettings();
}
private loadSettings() {
this.http.get<any[]>('/api/settings')
.subscribe(
(settings) => this.settings.next(settings),
(error) => console.error(error),
() => console.log("I'm complete")
);
//.subscribe({
//     next: (settings) => this.settings.next(settings),
//     complete: () => this.settings.next,
//     error: (s) => this.settings.next(s)
// });
}
getSettings() {
return this.settings.asObservable();
}
}

并在组件中

@Component({
selector: 'app',
templateUrl: 'app.component.html'
})
export class AppComponent {
settings: any[];
constructor(settingsService: SettingService){ }
ngOnInit() { 
this.settingsService.getSettings().subscribe(
(settings) => this.settings = settings
);
}
}

顺便说一句:你确定你从服务器收到数组([](而不是一个对象({}(吗? 如果你收到一个对象,你应该改变:

private settings = new BehaviorSubject<any[]>([]);
private settings = new BehaviorSubject<any>({});
this.http.get<any[]>('/api/settings')
this.http.get<any>('/api/settings')
settings: any[];
settings: any;

相关内容

最新更新