我正在使用RxJs 6运行Angular 6。
我试图从paramMap中获取值并将其分配给属性。路线看起来像这样:
{
path: 'post/:postName',
component: PostComponent
}
帖子组件目前看起来像这样:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { switchMap } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import * as matter from 'yaml-front-matter';
import { Post } from '../../models/post';
@Component({
selector: 'blog-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css'],
encapsulation: ViewEncapsulation.Emulated
})
export class PostComponent implements OnInit {
created: Date;
postName = '';
markdown = '';
title = '';
loading = true;
author = '';
constructor(private route: ActivatedRoute) { }
async ngOnInit () {
this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
of(params.get('postName'))
)
).subscribe(d => this.postName = d);
const file = await fetch(`/_posts/${this.postName}.md`);
const text = await file.text();
const content = text.trim();
this.parseFrontMatter(content);
}
parseFrontMatter (content: string) {
const frontMatter: Post = matter.loadFront(content);
this.title = frontMatter.title;
this.author = frontMatter.author;
this.created = frontMatter.created;
this.markdown = frontMatter.__content;
this.loading = false;
}
}
在ngOnInit中是用于从paramMap中获取值的代码。除非您尝试使用其他参数路由回post组件,否则此代码有效。
这可以在Devbin.io观察到。
答案 0 :(得分:9)
这是因为当您路由到同一组件时,不会调用ngOnInit。在您的情况下/ post / Angular-6-Router-How-To-Get-Route-Parameters和/ post / About正在触发相同的组件:post.component。
因此,为了完成这项工作,您可以在paramMap.pipe中调用subscribe中的函数。
您可以这样做:
[2.6,2.8]
答案 1 :(得分:3)
所以我克隆了回购并解决了问题。
替换它:
async ngOnInit () {
this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
of(params.get('postName'))
)
).subscribe(d => this.postName = d);
const file = await fetch(`/_posts/${this.postName}.md`);
const text = await file.text();
const content = text.trim();
this.parseFrontMatter(content);
}
以下内容:
ngOnInit() {
this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
of(params.get('postName'))
)
).subscribe(d => {
this.postName = d;
fetch(`/_posts/${this.postName}.md`)
.then(data => data.text()
.then(text => {
const content = text.trim();
this.parseFrontMatter(content);
}));
});
}
说明: 由于文件获取代码超出了Observable订阅方法,因此仅在组件初始化时才提取帖子。我移入并链接了承诺,然后将最终值传递给您的函数 parseFrontMatter