我正在尝试在我的组件模板中显示http get call响应数据。
我正在尝试从我的服务返回到我的组件的Observable中提取对象数据。我使用.subscribe方法,我得到“类型'订阅'不能分配给类型DataModel。类型订阅中缺少”属性'权利'。
不知道我哪里出错了。请指教 -
我的模特档案: -
export class DataModel {
public entitlement: string;
public serviceId: string;
public techType: string;
public avcId: string;
public accessTechnology: string;
public subAccessType: string;
}
我的组件文件: -
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { DataModel } from '../data-model';
import { DataFetchService } from '../data-fetch.service';
import { DataRequest } from '../data-request';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent{
serviceType: string;
serviceNumber: string;
cidn: string;
spid: string;
public data: DataModel;
constructor(private datafetchService: DataFetchService) {
}
datapull(): void{
this.data = this.datafetchService.getData(this.serviceType,this.serviceNumber,this.cidn,this.spid).subscribe(data => {this.data = data});
}
}
我的服务档案: -
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { DataModel } from './data-model';
import { UUID } from 'angular2-uuid';
@Injectable()
export class DataFetchService {
private url: string = "xxx";
private auth: string = "yyyy";
private xrid: string;
constructor(private http: HttpClient) {
}
ngOnInit() {
this.xrid = UUID.UUID();
}
getData(serviceType: string,serviceNumber: string,cidn: string,spid:string): Observable<DataModel> {
const params = new HttpParams()
.set('serviceType', serviceType)
.set('serviceNumber', serviceNumber);
const headers = new HttpHeaders()
.set("CIDN", cidn).set("SPID", spid).set("x-request-id", this.xrid).set("Authorization",this.auth);
return this.http.get<DataModel>(this.url,{headers,params});
}
}
答案 0 :(得分:4)
当您致电subscribe()
时,您会收到Subscription
个对象。您执行以下操作时已将该订阅分配给this.data
属性:
this.data = this.datafetchService.getData(this.serviceType,this.serviceNumber,this.cidn,this.spid).subscribe(data => {this.data = data});
只需删除作业,它就可以按预期工作:
this.datafetchService.getData(this.serviceType,this.serviceNumber,this.cidn,this.spid).subscribe(data => {this.data = data});
Typescript试图将Subscription
解释为DataModel
对象,这就是为什么它会告诉你&#34;键入&#39;订阅&#39;不能分配给DataModel类型。财产权利&#39;订阅类型&#34;&#34;