您如何发出一个 http get 请求 returns 一个 json 数组,该数组将用于填充 ngfor 指令?

How do you make an http get request that returns a json array which will be used to fill an ngfor directive?

我想发出一个 http get 请求,returns 一个 json 数据数组,将在 ngFor 循环中使用。我不确定执行此操作的最佳方法。 this.list 是要在 ngFor 指令中循环的列表。出于测试目的,json 文件位于我的本地计算机上。我已经查看了 Angular 2 文档,以及一个 udemy 课程,但无法弄清楚。我怀疑这很简单。

带有 ngFor 指令的组件。

constructor(private router:Router, private rec:RecommendationsService ){}
      ngOnInit(){
        this.rec.getRecommendations().subscribe(
          data=>{
            this.x = JSON.stringify(data);
            alert(this.x);
            this.list = this.x;
          }
        );
      }

获取请求位于服务中

import 'rxjs/Rx';

@Injectable()
export class RecommendationsService{

  url="//Users/Daniel/Desktop/Reccomendations.json";

  constructor(private http:Http){};

  getRecommendations(){
    return this.http.get(this.url).map(res => res.json);
  }
}

这是需要数据的 ngfor。

 <div *ngFor="let item of list, let i = index" data-toggle="modal" data-target="#recModal">
                <div class="row rowTopBuffer rowDiv" (click)="toModal(item.name, item.description, item.recLocLat, item.recLocLong, item.picturePath)">
                    <div class="col-sm-12 col-md-4 titleDiv" >
                        <img class="recommendationImages img-responsive img-rounded" src={{item.picturePath}}>
                    </div>
                    <div class="col-sm-12 col-md-6 descDiv">

                    <p class="itemTitle">{{item.name}}</p>
                    <p id="{{desc+i}}">{{item.description}}</p>

                    </div>
                </div>
            </div>

现在异常:当 运行 这段代码时 [object Object] 在控制台中抛出。

不要再次对该对象进行字符串化,因为您无法遍历字符串:)

ngOnInit(){
    this.rec.getRecommendations().subscribe(
        data => {
            this.x = JSON.stringify(data);
            alert(this.x);
            this.list = data;
        },
        error => console.log(error),
        () => console.log("done")
    );
}

同样在您的服务中调用 'json()' 方法,如下所示:

getRecommendations(){
    return this.http.get(this.url).map(res => res.json());
}

并且在您的模板中,您的 ngFor 用法有误。使用 ; 而不是 , 来分隔索引。

*ngFor="let item of list; let i = index"

在使用 angular 进行了更多工作之后,我学到了很多东西,并想为这个问题添加一个答案。您可以 return 接口本身,也可以 return 实现接口的 class。 Angular 将自行处理反序列化。

***************HTML

<div *ngFor="let employee of employees; let i = index;">
  <div>employee.Name</div>
  <div>employee.Id</div>
</div>

***************Typescript class 和界面

export interface Employee{
  Id:number;
  Name:string;
}

export class ResponseEmployee implements Employee{
  Id:number;
  Name:string;
}

*************** Http 服务

@Injectable()
export class EmployeeHttpService {


  constructor(private http: Http) {}

  getEmployees(city:string){

    var headers = new Headers();
    headers.append("Content-Type", "application/json");

    var url = “/api/endpoint/path”;

    return this.http
      .get(url, {headers:headers})
      .toPromise()
      .then((res)=> res.json() as ResponseEmployee[]);

  }

}

****************** 使用 employeeHttpService 的组件

@Component({
  selector: 'display-recommendations',
  templateUrl: './display-recommendations.component.html',
  styleUrls: ['./display-recommendations.component.sass']
})
export class DisplayEmployees implements OnInit {

  employees:ResponseEmployee[]=[];

  constructor(private employeeHttp:EmployeeHttpService){}

  ngOnInit() {

    this.employeeHttp.getEmployees()
      .then((data: ResponseEmployee[])=> {
        this.employees = data;
      })
      .catch((e:Error)=> this.handleError(e));
  }



}