Angular 6:如何订阅特定json响应密钥的数据

时间:2018-08-04 15:45:07

标签: angular angular6

我正在使用id

我有一个 contact-list.components.ts 从服务器检索联系人列表,该服务器以以下JSON格式返回数据。

Angular 6

我已经定义了 contact.model.ts

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": "9ab849a7-25c4-41df-9ac2-f9a122eed1ad",
            "first_name": "Anshuman",
            "last_name": "Upadhyay",
            ...
            "phone_numbers": [
                {
                    "id": "0bf22da0-b880-431b-b863-c10dac6c1ea9",
                    "phone": "9718996135",
                    ...
                }
            ],
            "emails": [
                {
                    "id": "16538e03-3257-4ac6-acfc-23e7c25757b9",
                    "email": "sushilphp85@gmail.com",
                    ...
                }
            ],
            "address": [
                {
                    "id": "54ad72b5-c570-4ea0-83ce-edf162b68f23",
                    "line_1": "Nirala",
                    ...
                    "state": {
                        "id": "e9e85f3b-bf2b-46e6-9209-4548bf619c83",
                        "name": "Uttar Pradesh",
                        ...
                        "country": {
                            "id": "6305ea1d-674b-470f-b1b9-31f46ca2bbec",
                            "name": "India",
                            ...
                        }
                    }
                }
            ]
        }
    ]
}

contacts.component.ts

export class Contact {
  id: string;
  first_name: string;
  last_name: string;
  full_name: string;
  gender: string;
  date_of_birth: string;
  avatar: string;
  primary_phone: string;
  primary_email: string;
  created: string;
  modified: string;
}

contact.service.ts

的内容
import { Component, OnInit } from '@angular/core';
import {ContactService} from '../contact.service';
import {Contact} from '../contact.model';

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

  contacts: Contact[];

  constructor(
    private contactService: ContactService
  ) { }

  ngOnInit() {
    this.getContacts();
  }

  getContacts(): void {
    this.contactService.getContacts().subscribe(
      contacts => this.contacts = contacts
    );
    console.log(this.contacts);    // prints undefined
  }

}

JSON响应位于import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable, of} from 'rxjs'; import {Contact} from './contact.model'; import {catchError} from 'rxjs/operators'; import {ResourceProviderService} from '../resource-provider.service'; import {AuthService} from '../auth/auth.service'; @Injectable({ providedIn: 'root' }) export class ContactService { private contactUrl = '/api/contacts/'; private static log(message: string) { console.log(`ContactService: ${message}`); } constructor( private http: HttpClient, private resource: ResourceProviderService, private auth: AuthService ) { } getContacts(): Observable<Contact[]> { const url = this.resource.url + this.contactUrl; return this.http.get<Contact[]>(url) .pipe( catchError(this.handleError('getContacts', [])) ); } private handleError<T> (operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // TODO: better job of transforming error for user consumption ContactService.log(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result. return of(result as T); }; } } 的请求URL的“网络”选项卡中,但无法将返回的数据保存到getContacts()中。

如何在Contacts类对象中设置返回的JSON数据?

2 个答案:

答案 0 :(得分:2)

getContacts(): void {
    this.contactService.getContacts()
    .subscribe((contacts: Contact[]) => {

         this.contacts = contacts

         // due to async nature of observable, this.contacts gets data at some point of time
         // So, out side of subscribe block, it won't be resolved when that line executes

         console.log(this.contacts);    // should print the actual value coming from backend
    });

}

答案 1 :(得分:1)

只需将console.log移动到订阅函数eq中即可。

getContacts(): void {
  this.contactService.getContacts().subscribe(contacts => 
  {
    this.contacts = contacts;
    console.log(this.contacts);
  }
  );
}