3

我想发出一个 http get 请求,该请求返回要在ngFor循环中使用的 json 数据数组。我不确定执行此操作的最佳方法。this.listngFor指令中要循环的列表。出于测试目的,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]。

4

2 回答 2

1

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

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"
于 2016-07-07T13:15:18.890 回答
1

在使用 Angular 进行了更多工作之后,我学到了很多东西,并想为这个问题添加一个答案。您可以返回接口本身,也可以像这样返回实现该接口的类。Angular 将负责反序列化本身。

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

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

*************Typescript 类和接口

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));
  }



}
于 2017-11-07T07:48:11.327 回答