【问题标题】:What is the correct syntax for my Angular get request? [duplicate]我的 Angular 获取请求的正确语法是什么? [复制]
【发布时间】:2017-05-19 16:35:18
【问题描述】:

我试图通过在后端创建一个端点并使用 Angular Http 服务查询它来通过 ID 获取用户。

正确的语法是什么?

这是我当前的代码:

服务

voteOn(poll: Poll, userID: string, choice: number) {
  var user;
  this.http.get('/'+userID)
  .map(response => response.json())
  .subscribe(json => user = json )
        user.votes.push({poll, choice });
        const body = JSON.stringify(user);
        const headers = new Headers({'Content-Type': 'application/json'});
        const token = localStorage.getItem('token')
            ? '?token=' + localStorage.getItem('token')
            : '';
        return this.http.patch('https://voting-app-10.herokuapp.com/user'+token, body, {headers: headers})
            .map((response: Response) => response.json())
            .catch((error: Response) => {
                this.errorService.handleError(error);
                return Observable.throw(error);
            })
            .subscribe();
}

路线

router.get('/:userid', function (req, res, next) {
  var userId = req.params.userid;
  UserModel.findById(userID, function (err, user) {
    return res.send(user);
  });
});

显然这是不正确的。调用 user.votes.push 时未定义用户变量。如何正确地将第一个查询的结果分配给用户?


解决方案:

voted(poll: Poll, userID: string, choice: number) {
      var user;
      this.http.get('/'+userID)
      .map(response => response.json())
      .subscribe(
            json => {
              user = json;
              var result = "";
              for (var i = 0; i < user.votes.length; i ++) {
                if (user.votes[i].poll == poll.pollId) {
                  result = "disabled";
                  if (user.votes[i].choice == choice) {
                    result =  "cheked";
                  }
                }
              }
              console.log("RESULT:"+result);
              return result;
          }
      )
    }

【问题讨论】:

  • 你是什么意思“正确的语法”?您是否从编译器收到语法错误?给minimal reproducible example。如果您只是说“我该怎么做”,那么我建议您进行一些研究;从官方文档开始。
  • @jonrsharpe 我已经阅读了文档。我知道我可以使用哪些方法,但是对于 Angular,我在这种情况下的实施遇到了一些麻烦。
  • 然后具体说明“麻烦” - 错误?意外行为?帮助其他人理解并重现您的问题。并且请不要回滚有效的编辑。
  • @jonrsharpe 你是对的。让我编辑我的问题。
  • 在问题中输入minimal reproducible example。就目前而言,尽管有缩进,但您仍试图在 订阅之外 操作 user 尚不可用的地方。 Observables 是异步的,这就是它们的重点;参见例如stackoverflow.com/q/37867020/3001761.

标签: javascript node.js angular service


【解决方案1】:

这里只说 Angular2 方面(不像 Express 那样熟悉,但路由处理程序看起来不错):

在高层次上,这看起来是合理的。你的核心问题是你在传递给 Observable.map() 的 lambda 中返回一个订阅,它将把它包装在一个 Observable: Observable 中。通常,您希望从客户端方法返回 Observable 而不是 Subscription,并让使用客户端的人决定如何订阅结果:

return this.http.patch(
                    'https://voting-app-10.herokuapp.com/user'+token, 
                    body, {headers: headers})
                .map((response: Response) => response.json())
                .catch((error: Response) => {
                    this.errorService.handleError(error);
                    return Observable.throw(error);
                })

这将返回 Observable,但如果你定义一个接口并将 response.json() 转换为它,你可以更好地输入。

为避免外部可观察包装,请考虑改用switchMap

this.http.get('/'+userID)
    .switchMap(user => 
        user.votes.push({poll, choice });
        const body = JSON.stringify(user);
        const headers = new Headers({'Content-Type': 'application/json'});
        const token = localStorage.getItem('token')
            ? '?token=' + localStorage.getItem('token')
            : '';
        return this.http.patch('https://voting-app-10.herokuapp.com/user'+token, body, {headers: headers})
            .map((response: Response) => response.json())
            .catch((error: Response) => {
                this.errorService.handleError(error);
                return Observable.throw(error);
            });
      )

对于 Angular Http 对象的一般用法(加上样板 REST 客户端基类),请查看:https://gist.github.com/lokitoth/d71794061e7e03bb8c1bf73648d6733d

【讨论】:

  • user.votes 属性 votes 在类型 response 上不存在。
  • 请看我编辑的问题代码。我不再有任何错误,但我不确定它是否会起作用。你怎么看?
猜你喜欢
  • 2013-08-23
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多