我的服务仅在appModule中列为提供者。它不在我的应用程序中的任何其他地方的提供者列表中。每当我离开使用它的组件并返回时,我在服务中设置的任何属性总是未定义的。这是我的服务......
LookupsService.ts
{% extends "puput/base.html" %}
{% block content %}
<style>
img.full-width {
width: 100%;
}
</style>
{{ block.super }}
{% endblock %}
我目前只在一个组件中使用此服务...
import {Injectable, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Http, Response} from "@angular/http";
import {environment} from "../environments/environment";
import {Lookups} from "./lookups.model";
@Injectable()
export class LookupService {
private baseUrl: string;
private lookups: Lookups;
constructor(private http: Http) {
this.baseUrl = `${environment.epiApiUrl}/lookups`;
}
getAll(): Observable<Lookups> {
// we should only hit the database to get all the lookups once
if (this.lookups) { // <-- this.lookups is ALWAYS undefined
return Observable.of(this.lookups);
}
else {
return this.http.get(`${this.baseUrl}`)
.map(this.extractData);
}
}
extractData(response: Response) {
let responseBody = response.json();
this.lookups = <Lookups>responseBody.data; // <--why isn't this remembered?
return this.lookups;
}
}
每当我换到不同的路由并返回时,服务每次都必须从api请求查找,因为this.lookups总是未定义的。不会再次调用LookupsService构造函数,但查找属性始终未定义。
答案 0 :(得分:3)
替换
.map(this.extractData);
通过
.map(response => this.extractData(response));
否则,this
不再绑定到当前对象。
恕我直言,呼叫map()
不应该有副作用。所以我会重构代码
return this.http.get(`${this.baseUrl}`)
.map(response => response.json().data)
.do(lookups => this.lookups = <Lookups>lookups);
这表明你已经
了