Fav*_*ave 4 api put mean-stack angular
我正在使用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);
});*/
}
Run Code Online (Sandbox Code Playgroud)
参数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());
}
Run Code Online (Sandbox Code Playgroud)
上面的http.post调用工作正常,但放置的updateUser根本不工作。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);
});
});
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我没有收到任何错误,但是就像我说的那样,服务器端的console.log没有被触发,这让我相信我在客户端调用中做错了什么。我只是不知道是什么。任何帮助表示赞赏!
小智 6
订阅可观察对象以“触发”它们
this.usersService.updateUser(this.currentUser._id).subscribe(response => {});
Run Code Online (Sandbox Code Playgroud)
另外,在您的服务器代码中
if(usr) {
updateLoggedIn();
} else {
console.log('something's wrong here');
}
Run Code Online (Sandbox Code Playgroud)
您别的都不返回,您应该在这里做些事情。
称呼subscribe:
this.usersService.updateUser(this.currentUser._id).subscribe((user) => {
let index = this.users.findIndex(u => u._id === user._id);
this.users[index] = user;
})
Run Code Online (Sandbox Code Playgroud)
或者,将可观察量分配给字段并使用async管道。
| 归档时间: |
|
| 查看次数: |
3230 次 |
| 最近记录: |