Angular 2订阅无法正常工作
问题描述:
我目前在Angular 2中遇到以下问题。Angular 2订阅无法正常工作
我的服务工作正常,我已将console.log()
添加到我的服务中,以检查它是否正在通过,它是哪里。我的服务如下所示:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/map';
@Injectable()
export class Service {
location: string;
constructor(private http: Http) {}
getCurrentLocation(): Observable<string> {
return this.http.get('service-method-here')
.map((result: Response) => result.json())
.map((data: any) => {
let location: string = '';
if(data) {
console.log(data.description);
location = data.description;
}
return this.location;
});
}
}
但是在我的组件内部,我打电话给这样的服务。它正在调用我的服务,因为我放在方法内的console.log()s
正在正确显示在控制台中。这是我如何调用我的组件里面的服务:
import { Component, OnInit } from '@angular/core';
import { FORM_DIRECTIVES } from '@angular/common';
import { Component } from '...';
import { Service } from '...';
@Component({
selector: 'selector',
templateUrl: '...',
styleUrls: ...,
directives: [FORM_DIRECTIVES, Component]
})
export class Component implements OnInit {
public locationName: string;
constructor(public service: Service) {
}
ngOnInit() {
this.service.getCurrentLocation()
.subscribe(data => {
console.log(data);
this.locationName = data
},
error => {
console.log('error');
});
}
的console.log()
组件内部返回undefined
。我的页面完整性的考虑上的HTML看起来像这样:
<h4>{{locationName}}</h4>
答
在服务这一行
location = data.description;
应该
this.location = data.description;
另有一个不同的位置比一个返回被设定为
@Injectable()
export class Service {
location: string;
constructor(private http: Http) {}
getCurrentLocation(): Observable<string> {
return this.http.get('service-method-here')
.map((result: Response) => result.json())
.map((data: any) => {
let location: string = '';
if(data) {
console.log(data.description);
this.location = data.description; // <==
}
return this.location;
});
}
}
答
有两个位置1)局部let location...
2)和组件this.location
.map((data: any) => {
//let location: string = '';
if(data) {
console.log(data.description);
// we should assign the components property, not the
// local variable
//location = data.description;
this.location = data.description;
}
// this is returned
return this.location;
});
而且因为组件是不是在所有
export class Component implements OnInit {
public locationName: string;
...
初始化,我们得到了一个未定义
享受Angular2和可观察反正;) –