【发布时间】:2018-05-22 22:20:10
【问题描述】:
我正在制作一个使用 MongoDB 数据库和 NodeJS 服务器的 Angular 应用程序。
我的想法是我创建一个应用程序,它现在只有一个帖子列表,旁边是详细帖子。这些组件很好地彼此相邻并且工作,但我有一个问题。当我尝试检索单个帖子时,我可以通过 console.dir(post) 看到一切都很好,并且该对象已传输到 Angular 应用程序。问题是当我尝试使用 post.content 时,我收到一条未定义的消息。
我已经搜索了几个小时,但似乎找不到原因。我将不胜感激您能给我的任何帮助。以下是所有信息,如果您需要查看其他信息,请告诉我。
提前致谢。
这是我要显示数据的 post-detail.component.html。
<div class="row">
<div class="col-xs-12">
<p>Content:</p>
<h1>{{ post.content }}</h1>
</div>
</div>
detail.ts 文件(我省略了导入)
@Component({
selector: 'app-post-detail',
templateUrl: './post-detail.component.html',
styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
post: Post = new Post();
id: string;
constructor(private postService: PostService,
private route: ActivatedRoute,
private router: Router) {
}
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.id = params['id'];
this.postService.getPost(this.id).then(res => {
console.dir(res);
console.dir(res.content);
this.post = res;
});
}
);
}
}
我用来检索实际数据的 post.service.ts:
@Injectable()
export class PostService {
postChanged = new Subject<Post[]>();
private headers = new Headers({'Content-Type': 'application/json'});
private serverUrl = environment.serverUrl + '/blogPosts/'; // URL to web api
private posts: Post[];
constructor(private http: Http) {
}
//this one DOES work
getPosts() {
console.log('Fetching BlogPosts from database.')
return this.http.get(this.serverUrl, {headers: this.headers})
.toPromise()
.then(response => {
this.posts = response.json() as Post[];
return response.json() as Post[];
})
.catch(error => {
return error;
});
}
getPost(index: string) {
console.log('Fetching individual BlogPost from database.');
console.log('index' + index);
if (index == null) {
console.log('null');
return null;
}
return this.http.get(this.serverUrl + index, {headers: this.headers})
.toPromise()
.then(response => {
console.dir(response.json().content);
console.dir(response.json());
return response.json() as Post;
})
.catch(error => {
return this.handleError(error);
});
}
}
后模型:
export class Post {
private id: string;
private _content: string;
constructor(values: Object = {}) {
Object.assign(this, values);
}
public get _id(): string {
return this.id;
}
public set _id(n: string) {
this.id = n;
}
public get content(): string {
return this._content;
}
public set content(n: string) {
this._content = n;
}
}
我在 Postman GET /blogPost/id 和控制台日志中添加了图像。 谢谢!
【问题讨论】:
-
{{ post._content }}是否可以进行更改?undefined这意味着它没有任何价值。你从端点收到什么?顺便说一句,为什么你只为_content而不是id使用命名约定'_'?我不是说它错了,但它背后的逻辑是什么? -
@DrNio 这是我从课程中获得的入门包,我自己没有命名。但正如您在我的控制台中看到的,该属性称为“内容”,而不是“_content”。
-
是的,我在控制台中看到了它,但是在您在组件(异步)操作中接收它之前,您需要使用具有
_content属性的new Post()对其进行初始化。这让我有点困惑。这又是一个想法 - 我不确定这是否是问题
标签: node.js mongodb angular mongoose