为什么我的http.put请求不起作用?均堆栈

时间:2018-01-05 08:33:21

标签: angular api mean-stack put

我正在使用API​​构建应用程序,到目前为止所有的http请求(get,post)都正常运行。现在我向我的服务添加了一个put请求,由于某种原因它无法正常工作。

这是我称之为服务功能的地方:

export class ChatStartComponent implements OnInit {

  @ViewChild('d1') d1:ElementRef;

  socket = io.connect('http://localhost:3000');

  constructor(private usersService: UsersService) {
    this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.currentUserName = this.currentUser.name;
    this.usersService.updateUser(this.currentUser._id); <--update Users does not
    /*this.usersService.getUsers()  <-- getUsers does work
      .subscribe(users => {
        this.users.push(users);
      });*/
  }

参数,currentUser._id确实存在,我可以在那时控制台记录它。

这是服务功能:

  addUser(newUser) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/api/user', JSON.stringify(newUser), {headers: headers});
  }

  updateUser(_id: string) {
    var set = {
      loggedIn: true
    };
    console.log(set, _id);
    return this.http.put('http://localhost:3000/api/update/' + _id, JSON.stringify(set))
      .map(res => res.json());
  }

上面的http.post调用工作正常,但updateUser put根本不工作。 console.log正在被触发,我确实记录了id,但http.put调用不起作用。

这是服务器端代码:

router.put('/update/:id', function(req, res) {
  console.log('hello there');
  let user = req.body;
  userService.update(req.params._id, req.body)
    .then(function() {
      res.sendStatus(200);
    })
    .catch(function(err) {
      res.sendStatus(err).send(err);
    });
});

这里没有触发console.log,这告诉我调用永远不会到达API。

这是在其中调用的服务器端服务功能(或者现在不会被调用):

function update(_id, set) {
  var deferred = Q.defer();

  db.users.findById(_id, function(err, usr) {
    if(err) deferred.reject(err.name + ': ' + err.message);

    if(usr) {
      updateLoggedIn();
    } else {
      console.log('something's wrong here');
    }
  });

  function updateLoggedIn() {
    db.users.update({ _id: _id}, { $set: set }, function(err, doc) {
      if(err) deferred.reject(err.name + ': ' + err.message);

      deferred.resolve;
    });
    return deferred.promise;
  }
}

我没有收到任何错误,但就像我说服务器端的console.log没有被触发一样,这让我相信我在客户端调用时出错了。我无法弄清楚是什么。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:4)

订阅Observables以“触发”它们

this.usersService.updateUser(this.currentUser._id).subscribe(response => {});

此外,在您的服务器代码中,

if(usr) {
  updateLoggedIn();
} else {
  console.log('something's wrong here');
}

你不会在别人身上归还任何东西,你应该在这里做点什么。

答案 1 :(得分:1)

致电subscribe

this.usersService.updateUser(this.currentUser._id).subscribe((user) => {
    let index = this.users.findIndex(u => u._id === user._id);
    this.users[index] = user;
})

或者,将observable分配给字段并使用async管道。

相关问题