7

Restangular POST を送信した後、応答オブジェクトを取得するにはどうすればよいですか?

 firstAccount.post("Buildings", myBuilding).then(function() {
   console.log("Object saved OK");
 }, function() {
  console.log("There was an error saving");
 });

新しいオブジェクト ID を取得しようとしています。

ありがとう。

4

3 に答える 3

2

Restangular を直接使用したことはありませんが、おそらく POST は ID を含む JSON オブジェクトを返す必要があります。次に、成功関数はそれをパラメーターとして受け入れる必要があります。

firstAccount.post("Buildings", myBuilding).then(function(resp) {
  console.log(resp.id);  // if the JSON obj has the id as part of the response
});
于 2013-06-17T07:48:03.263 に答える
0

改ざんされた POST は、投稿されたオブジェクトと同じオブジェクトが返されることを期待します。

これは、タイプスクリプトの定義で明確に見られます。タイプのオブジェクトを受け取り、ITypeAそれを のような URL で POSTするメソッドがあるとしますhttp://whatever/api/objects。REST API が 201 と、同じまたは異なる応答オブジェクトを含む json を返すとします。この場合、返される型がITypeB. 次に、restangular は の標準の POST を使用できずITypeA、 の応答を期待できませんITypeB。したがって、次のコードは正しくありませんITypeA

public postAnObject(objectToPost: models.ITypeA): ng.IPromise<models.ITypeB> {
     return this.restangular.all("objects")
            .post<models.ITypeA>(objectToPost)
            .then((responseObject: models.ITypeB) => {
                return responseObject;
            }, (restangularError: any) => {
                throw "Error adding object. Status: " + restangularError.status;
            });
}

これは customPOST を使用して解決できるため、上記のコードは次のようになります。

public postAnObject(objectToPost: models.ITypeA): ng.IPromise<models.ITypeB> {
     return this.restangular.all("objects")
            .customPOST(objectToPost)
            .then((restangularizedObjectTypeB: restangular.IElement) => {
                return restangularizedObjectTypeB.plain();
            }, (restangularError: any) => {
                throw "Error adding object. Status: " + restangularError.status;
            });
}

要約すると、注意すべき点がいくつかあります。

  1. Restangular は、成功したコールバック(その部分)で応答オブジェクトを取得できます。then
  2. メソッド.post(objectA)restangular を使用すると、objectA と同じタイプの応答を伴う成功したコールバックが期待されます。
  3. objectA を投稿したいが、応答 objectB (異なるタイプ) を取得する場合は、メソッドを使用します.customPOST(objectA)
  4. 重要: 応答は実際には、「実際の」応答オブジェクトをラップする「再言語化された」オブジェクトです。これは、応答にいくつかの角度変更メソッドが含まれていることを意味します。単に応答オブジェクトが必要な場合.plain()は、応答が実際にはITypeBオブジェクトではなく、restangular.IElement
于 2016-04-28T21:42:47.940 に答える