Angular 6 http响应问题

时间:2018-09-24 11:10:21

标签: angular http get

我发现HttpClient get请求的行为很奇怪。

响应1

API发送:

{
  payload: {
    object: {
      array: [1, 2, 3]
    }
  }
}

Angular收到:

{
  payload: {
    object: {
      array: []
    }
  }
}

响应2

API发送:

{
  payload: {
    array: [
      object: {
        array: [1, 2, 3]
      }
    ]
  }
}

Angular收到:

{
  payload: {
    array: [
      object: {
        array: [1, 2, 3]
      }
    ]
  }
}

有人遇到过这种行为吗?

更新

角度代码:

this.http
  .get(`instance/${id}`)
  .subscribe(
    response => log('get', response),
    error => log('error', error)
  );

API代码:

async function getInstance(req, res, next) {
  const instanceId = sanitize(req.params.id);

  if (!instanceId) {
    return utils.response[400](res, {
      message: 'Missed id'
    });
  }

  if (!instanceId.match(/^[0-9a-fA-F]{24}$/)) {
    return utils.response[400](res, {
      message: 'Wrong id'
    });
  }

  const model = models['instance'];
  const query = model
    .schema
    .findById(new mongoose.Types.ObjectId(instanceId))
    .populate('subInstance')
    .select(model.select);

  try {
    const instance = await query.exec();

    if (!instance) {
      return utils.response[404](res, {
        message: 'Instance not found'
      });
    }

    return utils.response[200](res, {
      instance: instance
      // I changed the response to this and everything works:
      // instance: [instance]
    });
  } catch (err) {
    return utils.response[501](res, err);
  }
}

更新2

响应功能代码:

function sendResponse(response, status, message, payload) {
  return response
    .status(status)
    .send({
      status: status,
      message: message,
      payload: payload
    });
}

module.exports = {
  200: (res, result) => sendResponse(res, 200, 'SUCCESS', result),
  201: (res, result) => sendResponse(res, 201, 'CREATED', result),
  204: (res, result) => sendResponse(res, 201, 'UPDATED', result),
  205: (res, result) => sendResponse(res, 201, 'REMOVED', result),
  301: (res, result) => sendResponse(res, 301, 'REDIRECTED', result),
  400: (res, result) => sendResponse(res, 400, 'NOT_VALID', result),
  401: (res, result) => sendResponse(res, 401, 'NOT_AUTHENTICATED', result),
  403: (res, result) => sendResponse(res, 403, 'NOT_AUTHORIZED', result),
  404: (res, result) => sendResponse(res, 404, 'NOT_FOUND', result),
  406: (res, result) => sendResponse(res, 406, 'WRONG_TYPE', result),
  409: (res, result) => sendResponse(res, 409, 'DUPLICATE', result),
  501: (res, result) => sendResponse(res, 501, 'ELSE_SERVER', result)
};

更新3

enter image description here

1 个答案:

答案 0 :(得分:-1)

这是由于异步行为所致,只需查看调用结束之前是否打印了角度。