javascript - @Injectable Service 不会转移到 Angular 5 中的组件

标签 javascript angular typescript observable

我正在尝试从我的 app.services.ts 文件中的 HTTP Get 请求创建一个 Observable,并让它在我的两个 Controller 之间移动数据。

我在我的 Controller 中定义了我想要定义的变量,并且我已经将服务注入(inject) Controller 的构造函数而没有任何错误,但是当我在我的应用程序加载时将变量记录到控制台时,我得到 undefined.

应用程序服务.ts:

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

@Injectable()
export class ApiService {

  constructor(private _http: Http) { }

  getContacts() {
    return this._http.get('assets/api/contacts.json')
    .map((response: Response) => response.json());
  }

}

应用程序组件.ts:

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {

  contacts: any[]; <--  //this is where I defined my variable 
  errorMessage: string;


  constructor (private _apiService: ApiService) {}

  ngOnInit(){ this.getContacts();
    console.log(this.contacts);   <-- //This is where I get undefined
  }

  getContacts() {
    this._apiService.getContacts()
    .subscribe(contacts => this.contacts = contacts,
     error => this.errorMessage = error);
  }

}

最佳答案

由于 contacts 已声明但未初始化且服务是异步的,因此未定义,打印出来时尚未准备好。您可以添加

 getContacts() {
    this._apiService.getContacts()
    .subscribe(
      (contacts) => {
        this.contacts = contacts;
        console.log(this.contacts);  // add it here
      },
      (error) => {
        this.errorMessage = error;
      }
    }

关于javascript - @Injectable Service 不会转移到 Angular 5 中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49328935/

相关文章:

javascript - 当有一位数时,秒表不加零

javascript - 在输入焦点上更改标签的字体大小

javascript - 如何在 RxJs Observable 中使用 Skip and Take

javascript - 有没有有效的方法将数据设置到MapObject?

javascript - 如何自动检测当前表单元素具有相同的类名

javascript - 从脚本与命令行在 Node 中分配全局变量

javascript - 如何改变 Angular 个人资料图片?

javascript - Angular 4 : How to show Re-login Dialog/Modal from intercepter

node.js - Azure Web App不启动 Node 服务器

angular - Typescript 非空数组返回大小为零的长度