Angular 6 如何通过管道传输 http 调用

Angular 6 how to pipe http call

我有一个 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;
  }
}

我个人会选择后者,这样可以确保事件仅在成功时发出。