【问题标题】:http.get not executed in Angular 8http.get 未在 Angular 8 中执行
【发布时间】:2020-02-07 12:24:37
【问题描述】:

我有一个方法可以从我的ngOnInit() 中的本地.txt 文件加载文本:

const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');

// This gets executed
console.log('FIRED');

this.http.get('assets/details.txt', {headers, responseType: 'text'})
    .pipe(
        map(data => {
            // This does not get executed!
            console.log('NOT FIRED');
        }),
        catchError((e: any) => {
            // Also no error Message
            console.log('NOT FIRED AS WELL');
            return throwError(e);
        }),
    );

    // This gets executed as well
    console.log('END');

我的错误在哪里,我该如何调试?

【问题讨论】:

    标签: javascript angular typescript rxjs angular8


    【解决方案1】:

    一个 observable 仅在订阅时执行。 http.get 返回一个 observable。修改你的代码如下

    this.http.get('assets/details.txt', { headers, responseType: 'text' })
      .pipe(
        map(data => {
          // This does not get executed!
          console.log('NOT FIRED');
        }),
        catchError((e: any) => {
          // Also no error Message
          console.log('NOT FIRED AS WELL');
          return throwError(e);
        }),
      ).subscribe((response) => {
        // HTTP call success. Use response here
      }, (error) => {
        // HTTP call failed. Handle error
      });
    

    【讨论】:

      【解决方案2】:

      您是否已添加订阅您的代码?

      this.http.get('assets/details.txt', {headers, responseType: 'text'})
          .pipe(
              map(data => {
                  // This does not get executed!
                  console.log('NOT FIRED');
              }),
              catchError((e: any) => {
                  // Also no error Message
                  console.log('NOT FIRED AS WELL');
                  return throwError(e);
              }),
          ).subscribe(); // here
      

      至于已经提到的文档

      因为 service 方法返回一个 Observable 的配置 数据,组件订阅方法的返回值。这 订阅回调将数据字段复制到组件的 config 对象,在组件模板中绑定数据 显示。

      【讨论】:

        【解决方案3】:

        虽然@TonyNgo 和@JohnsMathew 是完全正确的,但缺少的订阅是你所需要的,我希望你不会只是在那里使用你的回复。 在大多数情况下,我们试图传递 observable 而不是它的输出。 这样每个使用您的数据的组件都可以通过自己的逻辑对更改做出反应。 因此,在您的情况下,您很可能希望编写类似于以下内容的内容:

        ApiService.ts:

        getDetails(): Observable<any> {
          return this.http.get('assets/details.txt', {headers, responseType: 'text'});
        }
        

        SomeComponent.ts

        constructor(private apiService ApiService) {}
        
        someFunction() {
          const details$ = this.apiService.getDetails();
          details$.subscribe( detail => { 
            // execute all the things SomeComponent would need
          });
        }
        

        【讨论】:

          猜你喜欢
          • 2015-08-09
          • 1970-01-01
          • 2017-02-17
          • 1970-01-01
          • 2018-06-21
          • 2019-03-21
          • 2020-05-26
          • 1970-01-01
          • 2019-08-10
          相关资源
          最近更新 更多