我有一个HTTP服务,该服务使用HttpClient进行API调用:
//provider.service.ts
export interface Lesson {
id?: number,
name: string,
type: LessonType,
teacher_data: string,
student_data: string
}
export class ProviderService {
constructor(private http: HttpClient) {}
postLesson(form): Observable<Lesson> {
const body = this.getFormUrlEncoded(form.value);
return this.http.post<Lesson>('/api/lesson/', body, this.postHttpOptions);
}
}
我有一个使用此ProviderService的组件,如下所示:
onSubmit():void {
this.providerService.createLesson(lessonForm).subscribe(result=> {
console.log(result);
//do my stuff
});
}
}
它工作正常,一切都很好。现在,我想创建一个LessonService,以使所有http调用都通过该服务。它会缓存结果,发出更改等。
我是这样写的:
//updated lessons.component.ts
onSubmit():void {
this.LessonsService.createLesson(this.lessonForm).subscribe(result=> {
console.log(result);
//do my stuff
});
}
//lessons.service.ts
export class LessonsService {
constructor(private http: ProviderService) {}
@Output() lessonChange: EventEmitter<Lesson> = new EventEmitter();
public createLesson(form): Observable<Lesson> {
let observable = this.http.postLesson(form);
observable.pipe(
map(result => {
//this code is not executed, I do not understand why
this.lessonChange.emit(result);
return result;
})
);
return observable;
}
}
当我从HTTP提供程序获取结果时,我想发出一个事件。我做错了什么?
有两种方法可以执行此操作,一种是将放入pipe
变量声明中,然后使用tap
代替map
。
export class LessonsService {
@Output() lessonChange: EventEmitter<Lesson> = new EventEmitter();
public createLesson(form): Observable<Lesson> {
let observable = this.http.postLesson(form).pipe(
tap(result => {
//this code is not executed, I do not understand why
this.lessonChange.emit(result);
return result;
})
);
return observable;
}
}
另一种方法是创建对变量的订阅
export class LessonsService {
@Output() lessonChange: EventEmitter<Lesson> = new EventEmitter();
public createLesson(form): Observable<Lesson> {
let observable = this.http.postLesson(form);
observable.subscribe(result => {
//this code is not executed, I do not understand why
this.lessonChange.emit(result);
return result;
);
return observable;
}
}
我个人会选择后者,这样您可以确保仅在成功时才发出事件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句