我正在尝试从我的 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/