【问题标题】:Displaying json Data into a list in angular using an array and httpClient使用数组和 httpClient 以角度将 json 数据显示到列表中
【发布时间】:2020-08-24 08:28:34
【问题描述】:

我使用 Angular 8 来获取 JSON 数据并将其显示为列表,我不知道我错在哪里,因为它没有显示任何错误。并且视野是空的。如果有人有一个很好的眼睛或理解逻辑。我刚开始有角度,似乎没有发现问题所在。

video.service.ts

private _getUrl= "/api/videos";
constructor(private _http: HttpClient) { }

getVideos(){
 return this._http.get(this._getUrl).pipe(map((response: any) => response.json()));
}

video.center.component.ts

@Component({
  selector: 'app-video-center',
  templateUrl: './video-center.component.html',
  styleUrls: ['./video-center.component.css'],
  providers: [VideoService]
})
videos = [];
constructor(private _videoService: VideoService) { }

  ngOnInit(): void {
   this._videoService.getVideos().subscribe(data => this.videos = data);     
    console.log("videos array", this.videos); // even this is not working !
  }

video.list.component.html

<ul class="nav nav-pills nav-stacked">
    <li (click)="onSelect(video)" *ngFor="let video of videos"><a>{{video.title}}</a></li>
</ul>

【问题讨论】:

  • 你在*.component.ts文件中做服务的依赖注入了吗?
  • 是的,就像这样:constructor(private _videoService: VideoService) { }
  • 您在浏览器的开发工具中看到网络调用了吗?服务是否受到打击?如果是,那么检查响应部分?
  • 为什么要在网址前面加点?我只是想像@ngShravil.py 一样问你是否检查了开发工具中的网络选项卡。
  • 抱歉,URL 在 _getUrl:"api/videos" 上,是的,它在网络部分和响应中工作正常,它获取数据,但不知何故它没有显示它。空视图! HTML 也很好!

标签: node.js json angular mongodb angular-httpclient


【解决方案1】:

在 Angular 4.3 中引入了新的 HttpClient (@angular/common/http),其中响应对象默认为 json。所以你不需要映射答案。

所以只需返回 http 响应:


private _getUrl= "/api/videos";
constructor(private _http: HttpClient) { }

getVideos(){
 return this._http.get(this._getUrl);
}

【讨论】:

  • 你说得对,我在看到这个答案之前就想通了,只是尝试一下。我认为我们需要通过数据映射并传递答案,请您详细说明一下。所以我们不需要映射或管道响应?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多