我有一个从MongoDB中获取的待办事项列表,它们显示在一个页面上,当我点击一个时,它会打开另一个页面,其URL等于点击的待办事项。现在我试图从URL获取id并将其发送到节点服务器,但我无法得到它。
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
let todoId = params['userId'];
console.log(todoId);
}
);
}
console返回undefined。 我找到了一个解决方案,其中id由这行代码获取,但它只获取id一次,当我点击另一个todo时它不会记录任何内容。
let id = this.route.snapshot.paramMap.get('id');
console.log(id)
当我想用服务器向服务器发送请求时:
let id = this.route.snapshot.paramMap.get('id');
this.todoService.getSingleTodo(id)
.subscribe(
(todo: Todo) => {
this.todo = todo;
console.log(todo);
}
);
我在控制台“消息”中收到此错误:“转换为ObjectId失败,值为\”:id \“at path \”_ id \“
服务看起来像这样:
getSingleTodo(id) {
return this.http.get('http://localhost:3000/todos/:id')
.map( response => response.json().obj)
.map( todo => todo.map(todo => new Todo(todo.todoHeadline,
todo.todoDescription, todo._id)));
}
节点文件:
router.get('/:id', (req, res, next) => {
console.log(req.params.id);
Todo.findById(req.params.id, (err, singleTodo) => {
if (err) {
return res.status(500).json({
title: 'An error occured',
error:err
});
}
res.status(201).json({
message: 'Success',
obj: singleTodo
});
});
});
此控制台还会输出:id。
主路由文件
const APP_ROUTES: Routes = [
{ path: '', redirectTo: '/auth', pathMatch: 'full' },
{ path: 'todos', component: TodoComponent, children: TODO_ROUTES},
{ path: 'auth', component: AuthenticationComponent, children: AUTH_ROUTES }
];
儿童路线为待办事项
export const TODO_ROUTES: Routes = [
{path: 'todo/add', component: TodoAddComponent},
{path: ':id', component: TodoListComponent},
{path: 'edit', component: TodoEditComponent}
];
显示所有待办事项的HTML就像这样
<ul class="list-group">
<li class="list-group-item"
*ngFor="let todo of todos;"
[routerLink]="['/todos', todo.todoId]">{{todo.todoHeadline}}
</li>
</ul>
可能是什么问题?
答案 0 :(得分:0)
这就是这条线路的错误:
let todoId = params['userId'];
在路由中,您定义路径变量将命名为“id”:
{path: ':id', component: TodoListComponent},
因此,当您尝试访问路径变量userId时,它显然会返回undefined。