我正在进行API调用并存储一堆用户配置文件,我希望能够为每个配置文件动态创建卡(Angular Material Design md卡)。返回的配置文件数量可能会有所不同,因此这需要动态。从API响应动态创建md卡
这是我的组件文件,这使得JSONP请求并存储在profiles
变量的配置文件:
import {Component, Injectable, OnInit} from '@angular/core';
import {Jsonp} from '@angular/http';
@Component({
selector: 'app-staff',
templateUrl: './staff.component.html',
styleUrls: ['./staff.component.css']
})
@Injectable()
export class StaffComponent implements OnInit {
public searchField: string;
apiRoot = 'this/is/my/api/url';
public results: JSON;
public profiles;
constructor(private jsonp: Jsonp) {
}
ngOnInit() {
}
setSearchField(field: string){ // ignore this method
this.searchField = field;
console.log('Received field: ' + this.searchField);
}
search(term: string) {
const apiUrl = `${this.apiRoot}?search=${term}&rows=10&callback=JSONP_CALLBACK`;
return this.jsonp.request(apiUrl).map(results => { this.results = results.json(); console.log(this.results['profiles'][0]); this.profiles = results['profiles']; return results.json(); });
}
}
这是上面的组件,在那里我试图用*ngFor
创建一个模板的md-card
列表:
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-auto">
<ul>
<li *ngFor="let profile of profiles">
<md-card class="example-card">
<md-card-header>
<div md-card-avatar class="example-header-image"></div>
<md-card-title>{{profile.fullName}}</md-card-title>
<md-card-subtitle>Department</md-card-subtitle>
</md-card-header>
<img md-card-image src="../assets/image.png">
<md-card-content>
<p>
This section of the card will contain information about the result being searched for. It could also be
accompanied by additional information such as links.
</p>
</md-card-content>
<md-card-actions>
<button md-button>APPLY</button>
<button md-button>GO TO xyz</button>
</md-card-actions>
</md-card>
</li>
</ul>
</div>
</div>
</div>
我的简档数据是在一个阵列的形式(假设该阵列不超过10的长度),并采取以下形式:
0: {fullName: "Foo Bar", emailAddress: "[email protected]", image: "/profile/image/foobar/foobar.jpg", phoneNumber: "99999999"},
1: {fullName: "Foo Bar1", emailAddress: "[email protected]", image: "/profile/image/foobar1/foobar1.jpg", phoneNumber: "919999999"}
但是,没有md-card
正在呈现。我检查了profiles
不是空的。如何根据配置文件的数量动态创建卡片,并使用配置文件对象中的值填充内容?
你的'个人资料'数据是怎么样的?出租车你添加到你的问题? – Faisal
@Faisal我在我的问题中添加了更多关于'profiles'数据的信息。 – bawse
'this.profiles = results ['profiles']'应该是'this.profiles = this.results ['profiles']'或'this.profiles = results.json()['profiles']' – cyrix