저는 Angular 2 프런트 엔드에서 수신 및 표시 할 hal + json 객체를 생성하는 스프링 데이터 저장소를 보유하고 있습니다.Ang2의 Hal + JSON 객체의 정보를 구문 분석합니다.
핼 + JSON 개체 :
{
"_embedded" : {
"users" : [ {
"name" : "Bob",
"_links" : {
"self" : {
"href" : "http://localhost:4200/api/users/1"
},
"user" : {
"href" : "http://localhost:4200/api/users/1"
}
}
}, {
"name" : "Joe",
"_links" : {
"self" : {
"href" : "http://localhost:4200/api/users/2"
},
"user" : {
"href" : "http://localhost:4200/api/users/2"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:4200/api/users"
},
"profile" : {
"href" : "http://localhost:4200/api/profile/users"
},
"search" : {
"href" : "http://localhost:4200/api/users/search"
}
},
"page" : {
"size" : 20,
"totalElements" : 2,
"totalPages" : 1,
"number" : 0
}
}
나는이 API에 대한 GET 요청을 수행하는 서비스가있다.
user.service.ts :
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { User } from './user.model';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
@Injectable()
export class UserService {
constructor(private http: Http) {
}
findAllUsers(): Observable<Array<User>> {
return this.http.get('/api/users')
.map((response: Response) => response.json())
.map((data: Array<User>) => {
return data;
});
}
}
그런 다음 내 users.component는 서비스에서 findAllUsers 메소드를 호출합니다.
users.component.ts
마지막으로import { Component, OnInit } from '@angular/core';
import { User } from './user.model';
import { UserService } from './user.service';
@Component({
selector: 'app-users',
providers: [UserService],
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
users: User[];
constructor(private userService: UserService) {
}
ngOnInit(): void {
this.userService.findAllUsers().subscribe((data: Array<User>) => {
this.users = data;
});
}
}
, users.component.html는 :
내보기에<h4>Users:</h4>
<div *ngFor="let user of users">
{{user}}
</div>
나는 오류가 진술 얻을 : 내가 해결하는 방법을 잘 모르겠어요 Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
이. 내가 data
가 서비스에 반환되기 전에 디버거를 사용하려고하면
, 그럼 내 복도 + JSON 개체 = data
을 볼 수 있습니다, 그리고 내가 data._embedded_users
에서 원하는 정확한 정보를 볼 수 있습니다. 그러나 _embedded
은 내 사용자 모델의 속성이 아니기 때문에 사용자 []로 매핑 할 수 없습니다. 먼저 Hal + Json 객체에 대해 무언가를해야합니까?
''_links ''도 모든'user '에서 제거하지 않아도됩니까? –
@LambertoBasti 응답 데이터를 콘솔에 인쇄하면됩니다. 전체 구조를 볼 수 있습니다 –
실제로 데이터를 클래스에 바인딩해야하므로'.map()'연산자에서'_links' 필드를 삭제했습니다 –