拜托,我遇到过路线障碍的问题。更好的是,我需要一种方法从我的后端在我的角度服务中获取路由参数...我正在研究MEAN应用程序......
这个想法是,每篇文章都附有一系列评论,我已经在邮局的后端测试了这个,我得到了理想的结果......
我遇到的问题是,每当我导航到文章的评论路线时,articleId
都会返回undefined
下面是我的代码
my articles service that returns article and comments
getComments() {
const articleId = this.activatedRoute.snapshot.params['articleId'];
return this.http.get('http://localhost:7777/article/' + articleId + '/comments')
.map((response: Response) => {
const comments = response.json().obj;
const transformedComments: Comment[] = [];
for (const comment of comments) {
transformedComments.push(new Comment(
comment.body,
comment.username,
comment._id,
comment.articleId
));
}
this.comments = transformedComments;
console.log(transformedComments);
console.log(articleId);
return transformedComments;
})
.catch((error: Response) => Observable.throw(error.json()));
}
getComment() {
const headers = new Headers({ 'Content-Type': 'application/json' });
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
const articleId = this.activatedRoute.snapshot.params['articleId'];
// const commentId = this.activatedRoute.snapshot.params['commentId'];
return this.http.get('http://localhost:7777/article/' + articleId + '/comments/' + token, { headers: headers })
.map((response: Response) => {
const comment = response.json().comment;
const singleComment = new Comment(
comment.body,
comment.username,
comment._id,
comment.articleId
);
this.comment = singleComment;
return singleComment;
})
.catch((error: Response) => Observable.throw(error.json()));
}
我怀疑是我在角色服务中使用
activatedRoute.snapshot.params
的地方 加上我不确定,让我说我不知道怎么或为什么这篇文章没有得到路线的快照
我的评论组件
import { Component, OnInit, ViewEncapsulation, Input } from '@angular/core';
import { ArticleService } from '../../article.service';
import { User } from '../../../auth/user.model';
import { Comment } from '../../comment.model';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-article-comment-list',
templateUrl: './article-comment-list.component.html',
styleUrls: ['./article-comment-list.component.css'],
// providers: [ArticleService],
encapsulation: ViewEncapsulation.None
})
export class ArticleCommentListComponent implements OnInit {
private User: any;
article: any;
constructor(private articleService: ArticleService, private activatedRoute: ActivatedRoute ) { }
comments: Comment[];
ngOnInit() {
this.articleService.getComments()
.subscribe(
(comments: Comment[]) => {
this.comments = comments;
});
}
}