我有一个从Firebase检索的对象,该对象具有一系列属性,其中一个是数组。当我尝试使用*ngFor显示对象的属性并且必须显示数组时,我使用另一个*ngFor嵌套并循环遍历该数组的值。
当我查看结果时,我看到了除数组中的属性之外的属性值,但我觉得奇怪的是它们确实出现在控制台上,但被 Angular 注释掉了:
<div _ngcontent-c1="" id="langOutput">
<!--bindings={ "ng-reflect-ng-for-of": "Ada,R,D,EQ" }-->
</div>
使用的组件(console.log()
最终图像中的结果)
import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../services/project.service';
@Component({
selector: 'app-projectdetails',
templateUrl: './projectdetails.component.html',
styleUrls: ['./projectdetails.component.scss']
})
export class ProjectdetailsComponent implements OnInit {
projects: any[] = [];
languajes: any[] = [];
constructor(private projectService: ProjectService) { }
ngOnInit() {
this.projectService.getProject().subscribe(projects => {
// tslint:disable-next-line:forin
for ( const id$ in projects) {
const p = projects[id$];
p.id$ = id$;
this.projects.push(projects[id$]);
}
});
this.languajes = this.projects;
console.log(typeof this.projects); // 1r output
console.log(this.languajes); // 2º output
}
}
从 Firebase 获取数据的服务
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class ProjectService {
projectsUrl = 'https://proyecto.firebaseio.com/projects.json';
constructor(private http: Http) { }
postProject(project: any) {
const newProject = JSON.stringify(project);
const headers = new Headers({
'Content-type' : 'application/json'
});
return this.http.post(this.projectsUrl, newProject, {headers}).map(res => {
console.log(res.json());
return res.json();
});
}
getProject() {
return this.http.get(this.projectsUrl).map( res => res.json());
}
}
模板HTML
<ng-container *ngFor="let project of projects; let i = index">
<input type="text" placeholder="Title" value="{{ project.title }}">
<input type="number" min="0" placeholder="Max. number of participants" value="{{ project.participants }}" >
<input type="text" placeholder="Repository" value="{{ project.repository }}">
<div class="langBox" *ngFor="let languaje of project.languajes; let i = index">
<p > {{ languajes[i] }}</p>
</div>
<textarea name="" id="" placeholder="Write a description" >
{{ project.description }}
</textarea>
</ng-container>
应该:
在这种情况下,也不需要索引。
原因是当在这段代码的范围内时:
所以,如果你愿意,你可以使用'project.languages[index]',但最好使用'language'。实际上,两个范围内都没有“语言”变量。