【发布时间】:2018-07-25 15:56:18
【问题描述】:
"@angular/core": "^5.2.0"
“rxjs”:“^5.5.6”
我是 Angular 框架的新手,目前正在创建一个可注入的服务类,这将使 WebAPI 调用从后端数据库中提取数据。
我想保留或避免来自使用此服务类的组件的后续调用。因为它一次又一次地调用相同的数据。
我觉得我犯了一个很小的错误并且无法抓住它。我想避免第二次通话的往返。 在第一次调用期间,我想将数据保存在 _dyndata 对象中。但不知何故,对于每个服务调用,它都会打印 console.log('Fresh call') 语句。
请建议我在哪里犯了错误。我想使用角度变化检测的内置功能。
我的服务类如下所示:-
@Injectable()
export class DynamicDataService {
private _dyndata: DynamicContent[];
constructor(private _httpObj: HttpClient, private http: Http) {
}
headers = new HttpHeaders({
'Content-Type': 'application/json'
});
getdynamiccontent(): Observable<DynamicContent[]> {
if (this._dyndata) {
console.log('data exists!')
return of(this._dyndata);
}
console.log('Fresh call');
return this._httpObj.get<DynamicContent[]>(environment.apiHost + 'DynamiContentforPage')
.pipe(tap(data => this._dyndata = data)
);
}
使用这个服务类的组件看起来像这样:-
import { Component, ElementRef, Input, Renderer, OnInit, Inject, DoCheck } from '@angular/core';
import { DynamicDataService } from './dynamicdata.service';
import 'rxjs/add/operator/filter';
import { DynamicContent } from '../interfaces/IDynamicContent';
@Component({
selector: 'CMSBlock',
template: `<div [innerHTML]="_dynmarkup | keepHtml"></div>`,
providers: [DynamicDataService]
})
export class DynamicDataComponent {
public markupcollection: DynamicContent[];
public savedmarkup: DynamicContent[];
@Input('key') key: string;
public _dynmarkup: any = '';
constructor(private dynamicdataService: DynamicDataService) {
console.log('cstor :: dynamicdata comp');
this.getCMSData();
}
public getCMSData() {
this.dynamicdataService.getdynamiccontent()
.subscribe(px => {
this.setUsersArray(px);
console.log(this.markupcollection);
});
}
setUsersArray(data) {
this.savedmarkup = data;
if (this.savedmarkup != undefined) {
var item = this.savedmarkup.find(fx => fx.Key == this.key);
this._dynmarkup = item.Text
}
}
}
【问题讨论】:
-
tap()函数有什么用? -
您是否在点击回调中设置了断点以确保它正确通过?
-
是的,它工作正常。
-
你一定是在某处做错了,它在这里工作正常angular5-http-client-service-demo-neerrq.stackblitz.io。您是在 SAME 模块中再次调用该方法吗?
-
啊——那将是时间问题。在实例化第二个时,第一个还没有完成加载数据。因此,当第二个请求开始时,_dyndata 为空,因此它会触发另一个请求。为避免这种情况,您需要在将这些组件包含到页面之前进行重组以加载数据。