簡體   English   中英

Angular2無法映射單個JSON對象?

[英]Angular2 unable to map a single JSON object?

如何映射和使用單個對象而不是數組的JSON響應?

最近,我開始向正在處理的項目中添加一項新功能,該功能應該是從API接收JSON響應,然后使用其中的數據填寫一個簡單的模板。 不難,對吧? 好吧,不...但是,是...

JSON響應的模擬版本:

{
    "id": 1,
    "name": "Acaeris",
}

profile.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Profile } from './profile';

/**
 * This class provides the Profile service with methods to read profile data
 */
@Injectable()
export class ProfileService {
    /**
     * Creates a new ProfileService with the injected Http.
     * @param {Http} http - The injected Http.
     * @constructor
     */
    constructor(private http: Http) {}

    /**
     * Returns an Observable for the HTTP GET request for the JSON resource.
     * @return {Profile} The Observable for the HTTP request.
     */
    get(): Observable<Profile> {
        return this.http.get('assets/profile.json')
            .map(res => <Profile>res.json())
            .catch(this.handleError);
    }

    /**
     * Handle HTTP error
     */
    private handleError (error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

profile.component.ts

import { Component, OnInit } from '@angular/core';
import { ProfileService } from '../services/profile/profile.service';
import { Profile } from '../services/profile/profile';

/**
 * This class represents the lazy loaded ProfileComponent
 */
@Component({
    moduleId: module.id,
    selector: 'sd-profile',
    templateUrl: 'profile.component.html',
    styleUrls: ['profile.component.css'],
})
export class ProfileComponent implements OnInit {

    errorMessage: string;
    profile: Profile;

    /**
     * Creates an instance of the ProfileComponent with the injected
     * ProfileService
     *
     * @param {ProfileService} profileService - The injected ProfileService
     */
    constructor(public profileService: ProfileService) {}

    /**
     * Get the profile data
     */
    ngOnInit() {
        this.getProfile();
    }

    /**
     * Handles the profileService observable
     */
    getProfile() {
        this.profileService.get()
            .subscribe(
                data => this.profile = data,
                error => this.errorMessage = <any>error
            );
    }
}

profile.ts

export interface Profile {
    id: number;
    name: string;
}

而且我只是想使用{{profile.name}}輸出它,但這最終會在控制台上顯示全部錯誤消息且沒有輸出。 如果在加載profile后嘗試檢查其內容,它會告訴我它是undefined

但是,這是令人困惑的部分。 如果我替換所有對Profile[]Profile引用,則將JSON包裝在一個數組中,然后添加*ngFor="let p of profile" abd use {{p.name}}一切正常。 不幸的是,在實際完成的應用程序中,我無法控制JSON格式。 那么,與將其作為對象數組進行處理相比,嘗試將其作為單個對象進行處理時我做錯了什么?

看起來表達式{{profile.name}}的配置文件變量在頁面呈現時未定義。 您可以嘗試添加一些吸氣劑,如下所示:

get profileName(): string { return this.profile ? this.profile.name ? ''; }

並在模板{{profileName}}上使用,也可以在模板上使用ngIf,如下所示:

<div *ngIf="profile">{{profile.name}}</div>

或更短(如drewmoore在以下評論中建議的那樣):

<div>{{profile?.name}}</div>

使用數組時,情況相同-最初渲染時數組未定義。 ngFor為您處理此問題,不呈現任何內容。 完成獲取“配置文件項”的異步操作后-會再次以正確的值重新呈現UI。

map函數返回Observables,它是元素的集合。 它的工作原理基本上與數組的map函數相同。

現在要解決,可以將Profile引用替換為Profile Profile[]並使用{{profile[0].name}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM