gpt4 book ai didi

typescript - Angular 2订阅不起作用

转载 作者:搜寻专家 更新时间:2023-10-30 21:24:38 27 4
gpt4 key购买 nike

我目前在使用 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;
});
}
}

关于typescript - Angular 2订阅不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37693976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com