Angular5 *ngfor 不工作,但没有错误
Angular5 *ngfor not working, but there is no error
我现在遇到了 Angular 的问题。
我想从我的服务器 API 读取数据,并希望在 html 文档中使用 *ngfor 显示它。
我可以从 API 接收数据,但无法显示它。
我从英雄之旅教程中获取示例代码并对其进行了更改:
数据通过我的 angular 应用程序。我可以 console.log 它并在 chrome 开发控制台中看到它。
我尝试显示从 api 获得的其他数据,并且它正在运行。可以看到heroes.components.ts.
中被注释掉的数据
谁能帮我解决这个问题?
如果您想查看更多代码,例如导入,请告诉我。但我想一切都需要导入,因为没有错误消息,我可以从我的 api 获取数据并且我可以显示一些数据(遗憾的是不是我需要的数据)。
我尝试了其他一些帖子中的一些想法来解决这个问题,但无法实现。
以下是一些代码片段:
这是我的 hero.service.ts
进口...
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import { Hero } from '../model/hero';
import { MessageService } from '../message.service';
import { Response } from '@angular/http/src/static_response';
getHeroes(): Observable<Hero[]> {
console.log("GET HEROES IN HEROES.SERVICE");
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(Hero => console.log(`fetched heroes: `)),
catchError(this.handleError('getHeroes', []))
);
//我也试过只使用 return this.http.get(this.heroesUrl);
这是我的
heroes.components.ts
import { Component, OnInit } from '@angular/core';
import { Hero } from '../../model/hero';
import { HeroService } from '../hero.service';
import { CommonModule } from '@angular/common';
import { Pipe } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Response } from '@angular/http/src/static_response';
// For use of map
import 'rxjs/Rx';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes: Observable<Hero[]>;
// I tried to display some data
// heroes: any[] = [
// {
// "name": "Douglas Pace"
// }
// ];
constructor(private heroService: HeroService) { }
ngOnInit() {
this.getHeroes();
// undefined
console.log("ONINIT");
console.log(this.heroes);
}
getHeroes(): void {
console.log("GET HEROES IN HEROES.COMPONENT");
this.heroService.getHeroes()
.subscribe(
function(response: Hero[]) {
console.log("RESPONSE IN HEROES COMPONENT");
console.log(this.heroes);
var res = response["data"];
// console.log(res.json());
this.heroes = res;
console.log(this.heroes);
console.log(response["data"]);
},
function(error) {
console.log("Error happened" + error)
},
function() {
console.log("the subscription is completed")
//This shows me the right data.
console.log(this.heroes[5].id);
console.log(this.heroes[5].titel);
console.log(this.heroes[5].name);
console.log(this.heroes[5].vorname);
}
);
}
我的 html 文件:
<h2>My Heroes</h2>
<!-- <input type=text ng-model="hero"> -->
// I gave it a try with and without *ngIf="heroes"
<!-- only show the list IF the data is available -->
<div *ngIf="heroes">
<h3>Heroes are available and are displayed</h3>
<li *ngFor="let hero of heroes">
{{hero.name}}
</li>
</div>
<button (click)="button()">
Suchen
</button>
<div *ngIf="heroes">
<table class="heroes">
<tr>
<th>Id</th>
<th>Titel</th>
<th>Nachname</th>
<th>Vorname</th>
</tr>
//I tried async as the data is maybe not available from the
beginning. Also tried async on hero as heroes is created on init
and single heros are added with the function getHeroes();
<tr *ngFor='let hero of heroes | async'>
<a routerLink="/detail/{{hero.id}}">
<td>{{hero.id}}</td>
<td>{{hero.titel}}</td>
<td>{{hero.name}}</td>
<td>{{hero.vorname}}</td>
</a>
<button class="delete" title="delete hero"
(click)="delete(hero)">x</button>
</tr>
</table>
</div>
<pre>{{heroes | json}}</pre>
如果有英雄界面。应该是我的模特。只需要姓氏和名字。
export interface Hero {
id?: string;
name: string;
titel?: string;
vorname: string;
}
JSON 我 return 从我的 API 编辑的。在线 Json 格式化程序说它是有效的 json.
{"status":"Success","data":
[{"id":"36","name":"Hero","vorname":"Super","titel":"Dr.",},
{"id":"34","name":"Man","Spider":"Ines","titel":""}],
"message":"Retrieved all HEROES"}
您的代码似乎没问题,但我在此处看到您的 json 格式错误
"titel":"Dr.",},
试试把 Dr 后面的逗号去掉试试看
"titel":"Dr."},
this.heroService.getHeroes()
.subscribe(
function(response: Hero[]) { }
您的问题可能出在这里。您的回复是一个对象(比方说,接口):
interface DataResponse {
success: string;
data?: Hero[];
}
因为你设置了response: Hero[]
,而你的Hero
界面中没有data
属性,所以response["data"]
returnsnull,你会永远不会得到你的数据。如果你 运行 response.data
,你可能会收到一条错误消息 data is not defined in Hero
等...
更改为以下内容:
this.heroService.getHeroes()
.subscribe((response: DataResponse) => {
this.heroes = response["data"];
});
我现在遇到了 Angular 的问题。 我想从我的服务器 API 读取数据,并希望在 html 文档中使用 *ngfor 显示它。 我可以从 API 接收数据,但无法显示它。 我从英雄之旅教程中获取示例代码并对其进行了更改: 数据通过我的 angular 应用程序。我可以 console.log 它并在 chrome 开发控制台中看到它。 我尝试显示从 api 获得的其他数据,并且它正在运行。可以看到heroes.components.ts.
中被注释掉的数据谁能帮我解决这个问题? 如果您想查看更多代码,例如导入,请告诉我。但我想一切都需要导入,因为没有错误消息,我可以从我的 api 获取数据并且我可以显示一些数据(遗憾的是不是我需要的数据)。
我尝试了其他一些帖子中的一些想法来解决这个问题,但无法实现。
以下是一些代码片段: 这是我的 hero.service.ts
进口...
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import { Hero } from '../model/hero';
import { MessageService } from '../message.service';
import { Response } from '@angular/http/src/static_response';
getHeroes(): Observable<Hero[]> {
console.log("GET HEROES IN HEROES.SERVICE");
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(Hero => console.log(`fetched heroes: `)),
catchError(this.handleError('getHeroes', []))
);
//我也试过只使用 return this.http.get
这是我的 heroes.components.ts
import { Component, OnInit } from '@angular/core';
import { Hero } from '../../model/hero';
import { HeroService } from '../hero.service';
import { CommonModule } from '@angular/common';
import { Pipe } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Response } from '@angular/http/src/static_response';
// For use of map
import 'rxjs/Rx';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes: Observable<Hero[]>;
// I tried to display some data
// heroes: any[] = [
// {
// "name": "Douglas Pace"
// }
// ];
constructor(private heroService: HeroService) { }
ngOnInit() {
this.getHeroes();
// undefined
console.log("ONINIT");
console.log(this.heroes);
}
getHeroes(): void {
console.log("GET HEROES IN HEROES.COMPONENT");
this.heroService.getHeroes()
.subscribe(
function(response: Hero[]) {
console.log("RESPONSE IN HEROES COMPONENT");
console.log(this.heroes);
var res = response["data"];
// console.log(res.json());
this.heroes = res;
console.log(this.heroes);
console.log(response["data"]);
},
function(error) {
console.log("Error happened" + error)
},
function() {
console.log("the subscription is completed")
//This shows me the right data.
console.log(this.heroes[5].id);
console.log(this.heroes[5].titel);
console.log(this.heroes[5].name);
console.log(this.heroes[5].vorname);
}
);
}
我的 html 文件:
<h2>My Heroes</h2>
<!-- <input type=text ng-model="hero"> -->
// I gave it a try with and without *ngIf="heroes"
<!-- only show the list IF the data is available -->
<div *ngIf="heroes">
<h3>Heroes are available and are displayed</h3>
<li *ngFor="let hero of heroes">
{{hero.name}}
</li>
</div>
<button (click)="button()">
Suchen
</button>
<div *ngIf="heroes">
<table class="heroes">
<tr>
<th>Id</th>
<th>Titel</th>
<th>Nachname</th>
<th>Vorname</th>
</tr>
//I tried async as the data is maybe not available from the
beginning. Also tried async on hero as heroes is created on init
and single heros are added with the function getHeroes();
<tr *ngFor='let hero of heroes | async'>
<a routerLink="/detail/{{hero.id}}">
<td>{{hero.id}}</td>
<td>{{hero.titel}}</td>
<td>{{hero.name}}</td>
<td>{{hero.vorname}}</td>
</a>
<button class="delete" title="delete hero"
(click)="delete(hero)">x</button>
</tr>
</table>
</div>
<pre>{{heroes | json}}</pre>
如果有英雄界面。应该是我的模特。只需要姓氏和名字。
export interface Hero {
id?: string;
name: string;
titel?: string;
vorname: string;
}
JSON 我 return 从我的 API 编辑的。在线 Json 格式化程序说它是有效的 json.
{"status":"Success","data":
[{"id":"36","name":"Hero","vorname":"Super","titel":"Dr.",},
{"id":"34","name":"Man","Spider":"Ines","titel":""}],
"message":"Retrieved all HEROES"}
您的代码似乎没问题,但我在此处看到您的 json 格式错误
"titel":"Dr.",},
试试把 Dr 后面的逗号去掉试试看
"titel":"Dr."},
this.heroService.getHeroes()
.subscribe(
function(response: Hero[]) { }
您的问题可能出在这里。您的回复是一个对象(比方说,接口):
interface DataResponse {
success: string;
data?: Hero[];
}
因为你设置了response: Hero[]
,而你的Hero
界面中没有data
属性,所以response["data"]
returnsnull,你会永远不会得到你的数据。如果你 运行 response.data
,你可能会收到一条错误消息 data is not defined in Hero
等...
更改为以下内容:
this.heroService.getHeroes()
.subscribe((response: DataResponse) => {
this.heroes = response["data"];
});