从API响应中动态创建md-card

baw*_*wse 9 typescript angular-material angular

我正在进行API调用并存储一堆用户配置文件,我希望能够为每个配置文件动态创建卡(Angular Material Design md-card).返回的配置文件数量可能不同,因此需要是动态的.

这是我的组件文件,它生成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(); });
  }

}
Run Code Online (Sandbox Code Playgroud)

这是上面组件的模板,我试图*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>
Run Code Online (Sandbox Code Playgroud)

我的配置文件数据采用数组的形式(假设数组的长度不超过10)并采用以下形式:

0: {fullName: "Foo Bar", emailAddress: "foobar@foobar.com", image: "/profile/image/foobar/foobar.jpg", phoneNumber: "99999999"},

1: {fullName: "Foo Bar1", emailAddress: "foobar1@foobar.com", image: "/profile/image/foobar1/foobar1.jpg", phoneNumber: "919999999"}
Run Code Online (Sandbox Code Playgroud)

但是,没有md-card渲染.我检查过那profiles不是空的.如何根据配置文件的数量动态创建卡片,并使用配置文件对象中的值填充内容?

cyr*_*r_x 4

您可以尝试使用BehaviorSubjectfromrxjs并从响应中发出配置文件。在您的模板中使用管道async。这将确保角度的变化检测能够检测到变化。

private readonly profiles$$ = new BehaviorSubject([]);
public readonly profiles$ = this.profiles$$.asObservable();

//  ...

search(term: string) {
  const apiUrl = `${this.apiRoot}?search=${term}&rows=10&callback=JSONP_CALLBACK`;
  return this.jsonp.request(apiUrl).map(res => {
    let results = res.json();
    this.profiles$$.next(results.profiles);
    return results;
  });
}
Run Code Online (Sandbox Code Playgroud)

并在您的模板中:

<li *ngFor="let profile of profiles$ | async">
  <!--  ... -->
</li>
Run Code Online (Sandbox Code Playgroud)

顺便说一句:@Injectable从组件中删除装饰器,组件不应该是injectable

注意:您确实应该考虑将 api 调用移至共享服务中,这将使组件的逻辑保持干净,并且您也可以在其他组件中使用它。您也可以了解redux“模式”,为此您可以查看@ngrx/store@ngrx/effects更多信息可以在@ngrx/platform monorepo找到。它将使您能够对应用程序的状态进行巨大的控制,并且可以更轻松地管理数据并控制来自外部 API 的请求/响应。