【问题标题】:Angular 5 GET data with Observable and HttpClient - Fetching data from Web APIAngular 5 GET data with Observable and HttpClient - 从 Web API 获取数据
【发布时间】:2018-04-02 23:20:45
【问题描述】:

在使用少数可用的 Angular 5 Typescript 文档,了解如何使用 Observable 和 HttpClient 实现 CRUD 方法的新方法时,我想出了下一个代码,但仍然坚持显示来自 Web API 的数据:

这是我的模型:

export interface Value {
    id: number;
    name: string;
  }

我的服务:

export class ValueService {
  baseUrl = environment.apiUrl;

  constructor(private authHttp: HttpClient) {}

  getValues() {
    return this.authHttp
      .get<Value[]>(this.baseUrl + 'values', { observe: 'response'});
      // here my baseUrl is 'http://example.com/api/'
  }
}

我的组件:

@Component({
  selector: 'app-values',
  templateUrl: './values.component.html',
  styleUrls: ['./values.component.css']
})
export class ValuesComponent implements OnInit {

  values: Value[];

  constructor(private valueService: ValueService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.values = data['values'].result;
    });
  }
}

最后,我的模板:

<ul>
  <li>
    <div *ngFor="let value of values | async"> {{value.name}}</div>  
  </li>
</ul>

我的数据显示在带有 HTTP 200 结果的浏览器控制台中,但不在我的页面上,我缺少什么才能让它在我的页面上呈现?

【问题讨论】:

    标签: typescript httpclient observable angular5


    【解决方案1】:

    不确定您为什么要调用activatedRoute,因为它没有链接到您的ValueService。您应该显式调用 valueService 来获取数据。

    例如。在你的 ngOnInit()

    this.valueService.getValues().subscribe(response=> {
       // get your data here
    });
    

    还请查看您的 ValueService.getValues()。这是一个适用于我们项目的简单实现。您可以稍后映射您的数组。

    return this.http.get(url)
      .map((res: any) => res.json())
      .catch(error => Observable.throw(error.json()));
    

    顺便说一句。不确定您的异步过滤器是什么。它有什么作用?

    【讨论】:

      【解决方案2】:

      不确定您也在使用您的 ActivateRoute 做什么,我建议将它与您的 get data 方法分开。

      您的 getValues() 方法将返回一个 Observable,您将在组件中订阅它以将数据存储到 values 数组中。

      您不需要使用 |在你的 html ngFor 循环中异步,除非你正在循环一个 Observable,但在这种情况下,你订阅了 Observable 并将数据存储到一个数组中。

      服务:

      import { Injectable } from '@angular/core';
      
      @injectable()
      export class ValueService {
        baseUrl = environment.apiUrl;
      
        constructor(private authHttp: HttpClient) {}
      
        getValues(): Observable<HttpResponse<Value[]>> {
          return this.authHttp
            .get<Value[]>(this.baseUrl + 'values', { observe: 'response'});    
        }
      }
      

      组件:

      export class ValuesComponent implements OnInit {
      
        public values: Value[];
      
        constructor(private valueService: ValueService, private route: ActivatedRoute) { }
      
        ngOnInit() {
          this.valueService
              .subscribe(
                  data => this.values = data['values'].result; // console.log your data to make sure its returning the expected results
                  err => console.log(err);
               );
        }
      }
      

      HTML:

         <ul>
            <li>
              <div *ngFor="let value of values"> {{value.name}}</div>  
            </li>
          </ul>
      

      【讨论】:

      • 还将您的 authHttp 重命名为 http 除非它需要是经过身份验证的 http 调用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2018-06-17
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多