2017-07-23 133 views
1

我試圖使用Angular 4和隨機用戶API生成隨機用戶信息。每當我嘗試將接收到的數據打印到控制檯以檢查我是否獲得了我想要的內容時,我總是會收到「未定義」的消息,而不是我想要打印的內容。我得到了一個隨機用戶的對象,其中包含我需要的所有參數,但是如何打印並從該對象中獲取特定參數。我真的很喜歡和欣賞,如果有人會向我解釋這一點。先謝謝你。生成隨機用戶信息Angular 4

下面是我用得到的數據服務代碼:

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class UserdataService { 

    constructor(private _http: Http) { 
    } 

    getUserData(){ 

    return this._http.get('https://randomuser.me/api/?inc=name,location,nat,picture') 
    .map(res => res.json()); 

    } 

} 

這裏是組件代碼在那裏我得到的數據,並嘗試打印在控制檯:

import { Component, OnInit } from '@angular/core'; 
import { UserdataService } from '../../services/userdata.service'; 

@Component({ 
    selector: 'app-controller', 
    templateUrl: './controller.component.html', 
    styleUrls: ['./controller.component.css'] 
}) 
export class ControllerComponent implements OnInit { 

    constructor(private _randomUserService:UserdataService) { 

    } 

    ngOnInit() { 

    this._randomUserService.getUserData().subscribe((data)=>{ 
     console.log(data.name);//Try to print the name of the user as example 

    }); 
    } 
} 

回答

1

你不會從API那裏得到用戶,你會得到一個更復雜的對象,你需要從那個用戶那裏獲取用戶。因此,在服務映射到響應的結果屬性:

return this._http.get('https://randomuser.me/api/?inc=name,location,nat,picture') 
    .map(res => res.json().results[0]); 
+0

謝謝,這工作! – Keselme