【发布时间】:2016-05-31 19:18:34
【问题描述】:
我有这个从服务器返回的 json 数据,它不会映射到我的 typescript 对象。我确定这是一个小问题,但我找不到,我的队友也找不到。
JSON: {"labels: ["foo","bar"], "sums":null, "sid":0, "cid":0}
我的打字稿对象:
import {Claim} from './Claim';
import {ResponseInfo} from './ResponseInfo';
import {Rule} from './Rule';
import {ServiceLine} from './ServiceLine';
export interface ClaimResponse {
labels: string[];
}
这是我的服务:
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {RequestOptions, Http, Response, Headers, URLSearchParams} from '@angular/http';
import {ClaimResponse} from './ClaimResponse';
@Injectable()
export class EvaluationDetailService {
constructor(private http: Http) { }
getEvaluationDetail(): Observable<ClaimResponse> {
return this.http.get('./EvaluationDetail/GetEvaluationDetail')
.map((res: Response) => <ClaimResponse>res.json())
.do(data => console.log(JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
这是我的组件:
@Component({
selector: 'claim-evaluationdetail',
templateUrl: './Scripts/EvaluationDetail/evaluationdetail.component.html',
providers: [EvaluationDetailService, HTTP_PROVIDERS],
directives: [ResponseInfoComponent, ServiceLineComponent, OverlayPanel]
})
export class EvaluationDetailComponent implements OnInit {
constructor(private _evaluationDetailService: EvaluationDetailService) { }
claimResponse: ClaimResponse ;
visible: boolean = false;
showRules: boolean = false;
ngOnInit() {
this.getClaimResponse();
}
getClaimResponse() {
this._evaluationDetailService.getEvaluationDetail().subscribe(claimResponse => this.claimResponse = claimResponse);
}
}
从服务器返回的数据非常好(参见上面的 JSON 数据),但如果我尝试访问任何涉及“this.claimResponse”的内容,它是未定义的。
我做错了什么?
【问题讨论】:
-
您是否尝试在服务调用解决之前访问它?
-
我会提供与here相同的建议
-
“数据返回得非常好”是什么意思?是不是得到了用
.do(data => console.log(JSON.stringify(data)))打印的预期结果? -
所以澄清一下,你调用服务很好,在你的控制台中你看到的对象是你所期望的,但它没有绑定到你的组件对吗?您是否尝试过将控制台移至您的订阅,并在调试时更改名称以便清楚起见?例如: ...subscribe((newResponse) => {console.log('不要将我字符串化,因为控制台会弄清楚,新响应:',newResponse); this.claimResponse = newResponse;});如果您在该控制台中看到它没问题,我会查看订阅中是否丢失了“this”范围并在之前使用 that = this 并在 sub.. 中使用“that”
-
绑定效果如何?
标签: typescript angular