在AngularJS中创建新资源后,无法获取新对象属性

Cannot get the new object properties after the creation of a new resource in AngularJS

本文关键字:获取 新对象 属性 对象 新资源 AngularJS 资源 创建      更新时间:2023-09-26

我正试图在AngularJS中创建一个类型为Person的新资源。一旦创建了资源,我想获得新的资源id(由服务器返回)。

it('should get the new Person id after add', inject(function($httpBackend, Person) {
        $httpBackend.whenPOST('http://api.example.com/Persons').respond({ "id" : 32});
        var newPerson = new Person();
        newPerson.$save();
        expect(newPerson.id).toEquals(32);
 }));

我在因果报应中得到"预期未定义为32"。

我认为我的代码片段与信用卡代码片段末尾的$Resource文档提供的代码片段非常接近。

你知道我做错了什么吗?

您需要调用$httpBackend.flush()来刷新请求。

试试这个:

it('should get the new Person id after add', inject(function($httpBackend, Person) {
        $httpBackend.whenPOST('http://api.example.com/Persons').respond({ "id" : 32});
        var newPerson = new Person();
        newPerson.$save();
        $httpBackend.flush();
        expect(newPerson.id).toEquals(32);
 }));