我是Angular 4的新手。我想显示一个数组的内容。根据文档,我必须使用* ngFor指令来迭代和显示值。但我无法得到任何结果。
Home.component.html:
<h3 class="title">Top Restaurants near you</h3>
<div>
<div class="card" *ngFor="let restaurant of restaurants">
<span>{{restaurant._id}}</span>
<span>{{restaurant.name}}</span>
</div>
Home.component.ts:
import { Component, OnInit } from '@angular/core';
import { RestuarantService } from '../../services/restuarant.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
restaurant: Object;
constructor(private router: Router, private restaurantService: RestuarantService) { }
ngOnInit() {
this.restaurantService.getRestaurants().subscribe(restaurants => {
console.log(restaurants.restaurants[0]);
}, err => {
console.log(err);
return false;
});
}
}
Restaurant.service.ts:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class RestuarantService {
constructor(private http: Http) { }
getRestaurants() {
let headers = new Headers;
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/restaurants', { headers: headers }).map(res => res.json());
}
}
**编辑: 好吧,经过几次努力,并在Sajeetharan的帮助下,我发布了解决方案。
Home.Component.TS应该是这样的:**
import { Component, OnInit } from '@angular/core';
import { RestuarantService } from '../../services/restuarant.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
restaurants: any = [];
constructor(private router: Router, private restaurantService: RestuarantService) { }
ngOnInit() {
this.restaurantService.getRestaurants().subscribe(restaurants => {
this.restaurants = restaurants.restaurants[0];
console.log(JSON.stringify(this.restaurants));
}, err => {
console.log(err);
return false;
});
}
}
答案 0 :(得分:1)
您应该声明 restaurants
变量,并在 subscribe
export class HomeComponent implements OnInit {
restaurants: any = [];
constructor(private router: Router, private restaurantService: RestuarantService) { }
ngOnInit() {
this.restaurantService.getRestaurants().subscribe(restaurants => {
this.restaurants = restaurants;
}, err => {
console.log(err);
return false;
});
}
}