簡體   English   中英

Sails API不會將所有對象的屬性發送到前端Angular應用

[英]Sails API doesnt send all object's attributes to front end Angular app

我正在通過后端Sails API創建一個對象,以發送到我的前端應用程序。

這樣創建對象:

   getHommeAndChevre: function (req, res) {
      // console.log(req.param("id"));
      Trophe.find({foot: req.param('id')}, function(err, trophes){
        if(!trophes) {return res.status(400).end();}
        if(trophes){
          _.each(trophes, function(trophe, index){
            User.find(trophe.id, function(err, user){
              // console.log(user);
              if (trophe.trophe == 0) {var chevre = trophe; chevre.picture = user.picture; chevre.name = user.first_name; };
              if (trophe.trophe == 1) {var homme = trophe; homme.picture = user.picture; homme.name = user.first_name;};
              if (index == trophes.length - 1)
                return res.status(200).json({chevre: chevre, homme: homme});
            });
          });
        }
      });
    }

問題是我回到前端的對象chevrehomme不包含我在此處的函數中指定的picture屬性和name屬性:

 if (trophe.trophe == 0) {var chevre = trophe; chevre.picture = user.picture; chevre.name = user.first_name; };
                  if (trophe.trophe == 1) {var homme = trophe; homme.picture = user.picture; homme.name = user.first_name;};

這是我回到前端側的對象 在此處輸入圖片說明

如您所見,我的homme對象中沒有picturename屬性!

我在這里做錯了什么?

如果要查找單個記錄,請使用<model>.findOne()

<model>.find()始終返回Array ,因此當您執行User.find(trophe.id, function(err, user){} ,user.first_name將是undefined ,而是使用user[0].first_name

因此,您可能會有:

homme : {
    name : undefined
}

然后將其發送到res.json()進行字符串化處理(請參閱res.json() docs res.json() 在那時,它可能已被刪除:

sails> var trophe = {name : undefined}
undefined
sails> trophe
{ name: undefined }
sails> JSON.stringify(trophe)
'{}'
sails> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM