0

node.js コードに、循環参照を含む JSON オブジェクトがあります。このデータをブラウザーに送信するために、NPM モジュールの circle-jsonを使用してオブジェクトを文字列化し、循環参照をシリアル化しました。

var CircularJSON = require("circular-json");
app.get("/api/entries", function(req, res){ 
  contentClient.entries({"content_type": "xxxxxxxxxxx"}, function(err, entries){
    if (err) throw err;
    res.send(CircularJSON.stringify(entries));
  });
});

これは問題なく動作し、シリアル化されたデータを送信しres.send(); ます。フロントエンドの Angular コードで、循環参照を使用できるようにする必要があります。オブジェクトのシリアル化されたフィールドの 1 つは、クライアント側では次のようになります。"~0~fields~twitter~1"

ブラウザで次のことを試しました。

  1. circular-json.jsのバージョンをフロントエンド サイトにコピーしました
  2. index.html私のようにスクリプトにリンクされています:<script src="/framework/lib/circular-json.js"></script>
  3. CircularJson次のように変数を設定します。var CircularJSON = window.CircularJSON;
  4. 着信 JSON を次のように解析します。

    $http.get("/api/entries").then(function(res){ console.log(CircularJSON.parse(res.data[0])); });

次のエラーが表示されます。 SyntaxError: Unexpected token o

4

1 に答える 1

0

1回限りの呼び出しでは、次のように $http を使用できると思います

function appendTransform(defaults, transform) {

  // We can't guarantee that the default transformation is an array
  defaults = angular.isArray(defaults) ? defaults : [defaults];

  // Append the new transformation to the defaults
  defaults.unshift(transform);
  return defaults;
}

$http({
  url: '...',
  method: 'GET',
  transformResponse: appendTransform($http.defaults.transformResponse,                function(value) {
    return CircularJSON.parse(value);
  })
});

または、インターセプターを定義できる呼び出しごとに、例を次に示します: https://docs.angularjs.org/api/ng/service/ $http

更新: Unshift は配列を返しません。コードを修正したので、動作するはずです。

于 2015-05-16T15:28:15.040 に答える