http 的映射返回空对象中的可观察结果
Mapping of http returned observable result in null object
我正在向我的后端 getTest 方法发出 http 请求。那就是从使用 fiddler 测试的服务器返回的数据:
{
"number": "1a",
"testId": 1,
"testNumber": 5,
"testDate": "2016-05-20T00:00:00",
"assignedPupils": [],
"unAssignedPupils": []
}
订阅有问题,或者更确切地说 - 我假设 - .map 函数有问题,但我不确定。当我尝试调试映射时,我从未进入 EditTest class :/ 并且错误消息显示绑定 html 中的错误,这已经太晚了。我需要知道为什么 'test' 对象未定义!
有人看到问题了吗?
export class EditTestComponent implements OnInit {
test: EditTest;
constructor(
private _testsService: TestsService,
private _routeParams: RouteParams)
{ }
ngOnInit() {
let id = this._routeParams.get('id');
this._testsService.getTest(id).subscribe(test => this.test = test.map(t => new EditTest(t)));
}
}
TestService.ts:
getTest(id) {
return this.http.get('api/tests/edit/' + id).map(res => res.json());
}
Html:
<div>
<label>id: </label>{{test.id}}
<label>number: </label>{{test.number}}
<label>date: </label>{{test.date}}
</div>
我得到这个异常:
XCEPTION: TypeError: Cannot read property 'id' of undefined in [{{test.id}}
in EditTestComponent@3:27]
您在 test
从后端获取指定值之前引用了 {{test.id}}
。该错误实际上会阻止脚本执行,甚至永远不会到达 map
。要解决此问题,请使用 Elvis 运算符 ?
<p>Employer: {{employer?.companyName}}</p>
The safe navigation operator (?) means that the employer field is optional and if undefined, the rest of the expression should be ignored.
这样使用:
<div>
<label>id: </label>{{test?.id}}
<label>number: </label>{{test?.number}}
<label>date: </label>{{test?.date}}
</div>
此外,您没有显示 EditTest
的构造函数,所以我假设它获取属性并分配它们。
我正在向我的后端 getTest 方法发出 http 请求。那就是从使用 fiddler 测试的服务器返回的数据:
{
"number": "1a",
"testId": 1,
"testNumber": 5,
"testDate": "2016-05-20T00:00:00",
"assignedPupils": [],
"unAssignedPupils": []
}
订阅有问题,或者更确切地说 - 我假设 - .map 函数有问题,但我不确定。当我尝试调试映射时,我从未进入 EditTest class :/ 并且错误消息显示绑定 html 中的错误,这已经太晚了。我需要知道为什么 'test' 对象未定义!
有人看到问题了吗?
export class EditTestComponent implements OnInit {
test: EditTest;
constructor(
private _testsService: TestsService,
private _routeParams: RouteParams)
{ }
ngOnInit() {
let id = this._routeParams.get('id');
this._testsService.getTest(id).subscribe(test => this.test = test.map(t => new EditTest(t)));
}
}
TestService.ts:
getTest(id) {
return this.http.get('api/tests/edit/' + id).map(res => res.json());
}
Html:
<div>
<label>id: </label>{{test.id}}
<label>number: </label>{{test.number}}
<label>date: </label>{{test.date}}
</div>
我得到这个异常:
XCEPTION: TypeError: Cannot read property 'id' of undefined in [{{test.id}}
in EditTestComponent@3:27]
您在 test
从后端获取指定值之前引用了 {{test.id}}
。该错误实际上会阻止脚本执行,甚至永远不会到达 map
。要解决此问题,请使用 Elvis 运算符 ?
<p>Employer: {{employer?.companyName}}</p>
The safe navigation operator (?) means that the employer field is optional and if undefined, the rest of the expression should be ignored.
这样使用:
<div>
<label>id: </label>{{test?.id}}
<label>number: </label>{{test?.number}}
<label>date: </label>{{test?.date}}
</div>
此外,您没有显示 EditTest
的构造函数,所以我假设它获取属性并分配它们。