2017-04-14 4 views
3

저는 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 객체에 대해 무언가를해야합니까?

답변

4

먼저 Hal + Json 개체를 처리해야합니까?

분명하지 않습니까? 그냥

.map((data: Array<User>) => { 
    return data; 
}); 

가 잘못되기 전에, 때 실제로 데이터가 두 번째 map에 전달되는 것을 가정 사용자의 배열했다 당신이 있었다 어떤 서비스

findAllUsers(): Observable<Array<User>> { 
    return this.http.get('/api/users') 
    .map((response: Response) => response.json()) 
    .map((data: any) => { 
     return data._embedded.users as User[]; 
    }); 
} 

에서 데이터를 추출 그것은 전체 HAL 객체입니다. any으로 변경하면 두 개의 사용자를 추출 할 수 있습니다.

+0

''_links ''도 모든'user '에서 제거하지 않아도됩니까? –

+0

@LambertoBasti 응답 데이터를 콘솔에 인쇄하면됩니다. 전체 구조를 볼 수 있습니다 –

+0

실제로 데이터를 클래스에 바인딩해야하므로'.map()'연산자에서'_links' 필드를 삭제했습니다 –

관련 문제