【问题标题】:Angular 6 page not showing data from node backendAngular 6 页面未显示来自节点后端的数据
【发布时间】:2018-06-16 00:39:37
【问题描述】:

我想在前端使用 angular 6 显示从 api 返回的数据

这是我所做的:但没有显示数据:

component.htm:

<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Popular Movies</h3>
</div>
<div class="panel-body">
<div class="row">
    <div *ngFor="let movie of movies; let i=index" class="col-md-2">
        <div *ngIf="i < 6">
        <img *ngIf="movie.poster_path" class="thumbnail" src="http://image.tmdb.org/t/p/w500/{{movie.poster_path}}">
        <h4>{{movie.title}}</h4>
        <p>{{movie.release_date}}</p>

        <p><a class="btn btn-default" routerLink="/movie/{{movie.id}}">View details &raquo;</a></p>
      </div>
    </div>
</div>
</div>
</div>

component.ts:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { Location } from '@angular/common';
import { MoviesService } from '../movies.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.scss']
})
export class MoviesComponent implements OnInit {
   movies: any;

 constructor(private router: ActivatedRoute, private http: Http, private location: Location, private moviesService: MoviesService) {
      this.movies = [];
  }

  ngOnInit() {
    this.router.params.subscribe((params) => {
      const id = params['id'];
      this.moviesService.getMovies(id)
      .then(movies => {
          console.log(movies);
          this.movies = this.movies;
        });
   });
  }
}

service.ts:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import {Jsonp} from '@angular/http';
@Injectable({
  providedIn: 'root'
})
export class MoviesService {

  private apiUrl = 'http://localhost:8000/movies';


  constructor(private http: Http, private _jsonp: Jsonp) { }


  getMovies(id: string): Promise<any> {
      return this.http.get(this.apiUrl)
                 .toPromise()
                 .then(this.handleData)
                 .catch(this.handleError);
  }
  private handleData(res: any) {
       const body = res.json();
       console.log(body); // for development purposes only
       return body || {};
   }
 private handleError(error: any): Promise<any> {
     console.error('An error occurred', error); // for development purposes only
     return Promise.reject(error.message || error);
 }
}

当我运行我的应用程序时,没有显示从 api 返回的数据,当我在网络浏览器中检查响应时,返回的数据没有错误,

为什么数据没有显示在我的应用程序中?有什么建议我可能做错了吗?谢谢

【问题讨论】:

  • 您没有看到console.log() 打印的任何数据?

标签: javascript node.js angular typescript


【解决方案1】:

问题出在服务的 handleData 方法中。

您将变量body 声明为常量,这意味着它的值是不可变的。因此,您将其值设置为 res.json() 的尝试将被忽略。

改为:

let body = res.json();,你应该准备好了。

编辑:

还要注意res.json() 是不必要的;对 json() 的调用是自动应用的。您不需要在 Angular 6 中执行此操作。并且使用 HttpClient 服务,而不是 Http。

【讨论】:

  • 好的,你能告诉我这个句柄在删除 res.json 后应该是什么样子吗?
  • MoviesComponent.html:19 ERROR 错误:尝试比较“[object Object]”时出错。只允许使用数组和可迭代对象
【解决方案2】:

我想当您按下 F12 时,您的开发工具中出现 movies is undefined 错误。

原因是因为您的模板在 movies 数据从服务器获得其值之前首先加载(承诺上的异步调用) 然后模板正在尝试在 @ 中查找 movies 变量987654324@ 和 angular 捕获了未定义的错误。

为避免这种情况,请不要在数据尚不可用时显示模板。您可以使用*ngIf="movies" 或更好地使用ng-templateng-containerngTemplateOutlet 的组合来显示加载指示器。

<div *ngIf="movies" class="row">
    <div *ngFor="let movie of movies; let i=index" class="col-md-2">
        <div *ngIf="i < 6">
        <img *ngIf="movie.poster_path" class="thumbnail" src="http://image.tmdb.org/t/p/w500/{{movie.poster_path}}">
        <h4>{{movie.title}}</h4>
        <p>{{movie.release_date}}</p>

        <p><a class="btn btn-default" routerLink="/movie/{{movie.id}}">View details &raquo;</a></p>
      </div>
    </div>
</div>

但我通常使用ng-templateng-container*ngTemplateOutlet

<div class="panel-body">

<ng-container *ngTemplateOutlet="movies ? content : loading"></ng-container>

<ng-template #content>
<div class="row">
    <div *ngFor="let movie of movies; let i=index" class="col-md-2">
        <div *ngIf="i < 6">
        <img *ngIf="movie.poster_path" class="thumbnail" src="http://image.tmdb.org/t/p/w500/{{movie.poster_path}}">
        <h4>{{movie.title}}</h4>
        <p>{{movie.release_date}}</p>

        <p><a class="btn btn-default" routerLink="/movie/{{movie.id}}">View details &raquo;</a></p>
      </div>
    </div>
</ng-template>

<ng-template #loading>
   <div>loading data...</div>
</ng-template>

</div>
</div>

更新

找到了罪魁祸首。

您在ngOnInit() 上的分配错误

  ngOnInit() {
    this.router.params.subscribe((params) => {
      const id = params['id'];
      this.moviesService.getMovies(id)
      .then(movies => {
          console.log(movies);
          // Instead of this.movies = this.movies; use:
          this.movies = movies;
        });
   });
  }

【讨论】:

  • 控制台网络浏览器中没有错误我明白了:Angular 正在开发模式下运行。调用 enableProdMode() 以启用生产模式。 movies.component.ts:24 未定义
  • @HotZellah 我更新了我的答案,刚刚找到了导致此问题的原因
猜你喜欢
  • 2017-11-03
  • 2019-05-06
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
相关资源
最近更新 更多