繁体   English   中英

http.get 未在 Angular 中执行 8

[英]http.get not executed in Angular 8

我有一个方法可以从我的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');

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

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

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

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

至于文件已经提到

因为服务方法返回一个配置数据的 Observable,所以组件订阅了该方法的返回值。 订阅回调将数据字段复制到组件的配置 object 中,该配置在组件模板中绑定数据以进行显示。

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

ApiService.ts:

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

一些组件.ts

constructor(private apiService ApiService) {}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM