angular - 如何从 ParamMap 中获取路由参数并将其分配给属性
问题描述
我正在使用 RxJs 6 运行 Angular 6。
我正在尝试从 paramMap 中获取值并将其分配给属性。路线如下所示:
{
path: 'post/:postName',
component: PostComponent
}
post 组件当前如下所示:
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上观察到。
- 导航到帖子页面
- 点击唯一的帖子
- 现在尝试导航到关于页面,这只是另一篇文章。
- 请注意,即使 URL 已更新,它也不会路由到 About 页面。
完整的源代码可以在GitHub上找到
所有文档和其他 Stack Overflow 答案始终假定您要在 switchMap 函数中调用服务。官方文档在这里
我的问题是如何获取路线参数并将其分配给属性并在导航回同一路线时保持导航工作?
解决方案
这是因为当您路由到同一个组件时,不会调用 ngOnInit。在您的情况下 /post/Angular-6-Router-How-To-Get-Route-Parameters 和 /post/About 正在触发相同的组件:post.component。
因此,要完成这项工作,您可以在 paramMap.pipe 中调用 subscribe 内的函数。
你可以这样做:
ngOnInit() {
this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
of(params.get('postName'))
)
).subscribe((d) => {
this.postName = d;
this.postInit();
});
}
async postInit() {
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;
}
推荐阅读
- git - 实施 Dropbox .gitignore
- java - 如何在 ResourceBundleMessageSource 中设置默认语言环境?
- macos - MAMP pro 正在缓存
- arrays - for循环内的VBA If语句未评估true
- openstack - Ubuntu 18.04 LTS 上的 Openstack 什么是合适的分支
- javascript - 如何使用带有可选参数命名的 Apply 调用函数?
- python - 如果在 Python 中的类中引发任何异常,请断开与服务器的连接
- python - 从两个 numpy 数组创建字典
- android - 如何在 Android 中集成 DialogFlow V2?
- stanford-nlp - 斯坦福 CoreNLP:引用注释器