2017-01-24 1 views
0

나는 angular2를 처음 사용합니다. 여기, getLeftData()의 리턴 유형은 어떻게 특정 리턴 유형이 될 수 있습니까?
Angular 2 typescript에서 json 객체의 List 유형을 반환하는 방법은 무엇입니까?

HTTPTestService.ts :

@Injectable() 
export class HTTPTestService { 
    private siteUrl="https://api.stackexchange.com/2.2/sites"; 
    constructor(private _http: Http) { } 
    getLeftData(): Promise<Items[]> { 
     return this._http.get(this.siteUrl). 
     toPromise() 
     .then(response =>response.json().data as Items[]) 
    } 
} 

JSON 데이터 :

{ 
    "items": [ 
    { 
     "aliases": [ 
     "http://www.xyz.in", 
     "http://facebook.xyz.in" 
     ], 
     "styling": { 
     "tag_background_color": "#E0EAF1", 
     "tag_foreground_color": "#3E6D8E", 
     "link_color": "#0077CC" 
     }, 
     "related_sites": [ 
     { 
      "relation": "meta", 
      "api_site_parameter": "meta.xyz", 
      "site_url": "http://met.xyz.in" 
     }, 
     { 
      "relation": "chat", 
      "name": "Stack Overflow Chat" 
     } 
     ], 
     "markdown_extensions": [ 
     "Prettify" 
     ], 
     "launch_date": 1221436800, 
     "closed_beta_date": 1217462400, 
     "site_state": "normal", 
     "favicon_url": "https://cdn.sstatic.net/Sites/xyz/img/favicon.ico", 
     "name": "Stack Overflow", 
     "site_type": "main_site" 
    } 
    ] 
} 

사람의 도움이 있다면, 어떻게 각도 2 타이프 라이터에서 JSON 객체 목록의 반환 형식이 될 수 있을까?

+0

. 이것을 확인하십시오 게시물 http://stackoverflow.com/questions/37364973/angular-2-promise-vs-observable – alltej

답변

1

내가 정확한 문제가 무엇 아주 잘 모르겠지만,의 시도하자 ..

첫째 : 당신이해야한다 "모델"당신의 Items - 클래스!

둘째 : json().data 대신 json().items을 사용해야합니다!

아마이 도움이됩니다 : 당신은 대신 약속의 관찰 가능한을 사용해야합니다 https://plnkr.co/edit/gdwI1XfsUDCgZgoaKjce?p=preview

export class ItemModel { 
    aliases: string[]; 
    styling: { 
    tag_background_color: string, 
    tag_foreground_color: string, 
    link_color: string 
    }, 
    related_sites: { 
    relation: string, 
    api_site_parameter: string, 
    site_url: string, 
    name: string 
    }[], 
    markdown_extensions: string[], 
    launch_date: number, 
    closed_beta_date: number, 
    site_state: string, 
    // ... 
    // ... 
    name: string, 
    // ... 
    // ... 
} 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
     <p *ngFor="let item of _items">{{ item.name }}</p> 
    </div> 
    `, 
}) 
export class App { 
    name:string; 
    private _items: ItemModel[] = []; 

    constructor(private _http: Http) { 
    this.name = 'Angular2' 
    } 

    ngOnInit() { 
    this.getLeftData().subscribe(items => { 
     console.log(items); 
     this._items = items; 
    }); 
    } 

    public getLeftData(): Observable<ItemModel[]> { 
    return this._http 
     .get('https://api.stackexchange.com/2.2/sites') 
     .map(response => response.json().items); 
    } 
} 
+0

덕분에, 그것은 woking @ mxii이야 –

관련 문제