如何从ParamMap中获取route参数并将其分配给属性

Miz*_*-Mo 4 rxjs angular-routing angular

我用RxJs 6运行Angular 6.

我试图从paramMap中获取值并将其分配给属性.路线看起来像这样:

{
    path: 'post/:postName',
    component: PostComponent
}
Run Code Online (Sandbox Code Playgroud)

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

在ngOnInit中是用于从paramMap中获取值的代码.除非您尝试使用其他参数路由回post组件,否则此代码有效.

这可以在Devbin.io上观察到.

  1. 导航到帖子页面
  2. 点击唯一的帖子
  3. 现在尝试导航到另一个帖子的about页面.
  4. 请注意,即使更新了Url,它也不会路由到"关于"页面.

完整的源代码可以在GitHub找到

所有文档和其他Stack Overflow答案总是假设您要在switchMap函数中调用服务.官方文档在这里

我的问题是如何获取route参数并将其分配给属性并在导航回同一路线时保持导航工作?

小智 10

这是因为当您路由到同一组件时,不会调用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;
  }
Run Code Online (Sandbox Code Playgroud)

  • 我将这个标记为答案,因为另一个将我的 async/await 代码转换为我不想使用的链式承诺。两个答案都解决了这个问题。谢谢两位的帮助! (2认同)