无法使用 Angular js 2 打印数据



我不确定我哪里出错了,在服务器端和客户端都创建了一个平均堆栈应用程序。服务器端工作正常,我可以从表中发布,获取和删除数据,但无法显示组件.html文件中的获取数据。我已经共享了我的组件,服务和html文件,请找出错误所在。如果您需要任何其他文件,我可以共享。

This is ideas.component.ts
import { Component, OnInit } from '@angular/core';
import { IdeaService } from "../idea.service";
import { Idea } from "../idea";
@Component({
selector: 'app-ideas',
templateUrl:'./ideas.component.html',
styleUrls: ['./ideas.component.css'],
providers: [IdeaService]
})
export class IdeasComponent implements OnInit {
Ideas: Idea[];
idea: Idea;
Name: String;
ideas: String;
Comments: String
constructor(private ideaService: IdeaService) { }
ngOnInit() {
this.ideaService.getIdeas().subscribe(idea => this.idea = idea);
}
}
This ideas.component.html
<div class="container">
<div *ngFor="let idea of idea">
<div class="col-md-3">
{{idea.Name}}
</div>
<div class="col-md-3">
{{idea.ideas}}
</div>
<div class="col-md-3">
{{idea.Comments}}
</div>
<div class="col-md-3">
<input type="button" (click)="deleteContact(contact._id)" value="Delete" class="btn btn-danger">
<br>
<br>
</div>
</div>
</div>

This is idea.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Idea } from './idea';
import 'rxjs/add/operator/map';
@Injectable()
export class IdeaService {
constructor(private http: Http) { }
getIdeas() {
return this.http.get('http://localhost:3000/Demo_App/Home')
.map(res => res.json());
}
addIdeas(newIdea) {
var headers = new Headers();
headers.append('Content-Type', 'application/json')
return this.http.post('http://localhost:3000/Demo_App/ideas', newIdea, { headers: headers })
.map(res => res.json());
}
deleteIdea(id){
return this.http.delete('http://localhost:3000/Demo_App/idea/'+id)
.map(res => res.json());
}
}

This is idea.ts
export class Idea{
id?;
Name:String;
ideas:String;
Comments:String;
}

你必须在 html 中使用 idea 而不是 ngFor 中的想法来显示值

<div class="container">
<div *ngFor="let idea of ideas">
<div class="col-md-3">
{{idea.Name}}
</div>
<div class="col-md-3">
{{idea.ideas}}
</div>
<div class="col-md-3">
{{idea.Comments}}
</div>
</div>
</div>

您可以从下面的链接获取有关在 Angular 中显示数据的更多信息 https://angular.io/guide/displaying-data

你应该在循环中使用"idea"而不是"ideas" 您的问题是在订阅中您正在覆盖您的想法对象。您不会将任何内容推送到数组中。

您需要进行的更改:

ideas.component.ts

ideasArray: Idea[] = [];
ngOnInit() {
this.ideaService.getIdeas().subscribe(idea => 
{this.idea = idea;
if(idea){ 
this.ideasArray.push(idea);});
}

想法.组件.html

<div class="container">
<div *ngFor="let idea of ideasArray">
<div class="col-md-3">
{{idea.Name}}
</div>
<div class="col-md-3">
{{idea.ideas}}
</div>
<div class="col-md-3">
{{idea.Comments}}
</div>
</div>
</div>

相关内容

  • 没有找到相关文章

最新更新