我目前在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>
答案 0 :(得分:3)
在您的服务中这一行
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 :(得分:1)
有两个位置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;
});
因为组件根本不是init
export class Component implements OnInit {
public locationName: string;
...
我们得到未定义的