首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从ParamMap中获取路由参数并将其分配给属性

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

Stack Overflow用户
提问于 2018-06-05 16:48:45
回答 2查看 15.2K关注 0票数 7

我用RxJs 6运行角形6。

我试图从paramMap中获取值,并将其分配给一个属性。路线如下:

代码语言:javascript
复制
{
    path: 'post/:postName',
    component: PostComponent
}

post组件当前如下所示:

代码语言:javascript
复制
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上观察到。

  1. 导航到posts页面
  2. 点击唯一的帖子
  3. 现在,尝试导航到有关页面,这只是另一篇文章。
  4. 注意,即使更新了Url,它也不会路由到About页面。

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

所有的文档和其他堆栈溢出答案总是假设您想要在switchMap函数中调用一个服务。正式文档是这里

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-05 18:46:20

这是因为当您路由到同一个组件时,不会调用ngOnInit。在您的例子中,/post/Angular-6-Router-How-To-Get-Route-Parameters和/post/ your触发了相同的组件: post.component。

因此,要完成这项工作,您可以在paramMap.pipe中调用订阅内部的函数。

你可以这样做:

代码语言:javascript
复制
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;
  }
票数 17
EN

Stack Overflow用户

发布于 2018-06-05 18:44:13

所以我克隆了回购并修复了这个问题。

代之以:

代码语言:javascript
复制
   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);
      }

有以下几点:

代码语言:javascript
复制
  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);
          }));
    });
  }

说明:只有在组件初始化时才会获取这些帖子,因为您的文件提取代码在可观察的订阅方法之外。我进入并链接了承诺,然后将最后的值传递给函数parseFrontMatter。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50705214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档