Router Link不会使用其他占位符加载另一个页面.这是正确的方法吗? [英] Router Link is not loading another page with different placeholder. Is this the right way to do it?

查看:129
本文介绍了Router Link不会使用其他占位符加载另一个页面.这是正确的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的博客博客构建基于Angular(v6.2.9)的主题,这是我遇到此问题的时间.我正在尝试从我的博客加载页面.为此,我创建了组件和相应的路径(请参见下面的代码).博客上的页面格式为http://{blogname}.blogspot.com/p/{permalink}.我当前代码的问题是,当单击具有相应匹配路由的routerLink时,它会首次完全加载任何页面.但是,当单击仅具有不同占位符的链接时,仅URL会在地址栏中更改,但屏幕上不会加载任何内容.

I'm trying to build an Angular (v6.2.9) based theme for my blogger blog and this is when I encountered this problem. I'm trying to load pages from my blog. For this, I created components and corresponding paths (see the code below). Pages on blogger have the format http://{blogname}.blogspot.com/p/{permalink}. The problem with my current code is that it loads any page perfectly fine for the first time when routerLink with the corresponding matching routes is clicked. But when a link with just different placeholder is clicked, only the URL changes in the address bar but nothing loads on screen.

我尝试从content.component.ts将变量打印到控制台上进行调试,但是我得到了预期的结果.变量仅打印一次.我还尝试了routerLink的变体,带和不带[]括号,但没有运气.我想router.navigate()也将不起作用.鉴于此,我怀疑我的设计或代码有问题.

I tried printing variables onto the console from content.component.ts for debugging, but I get the expected results. The variables get printed just for once. I also tried variations of routerLink with and without [] brackets but no luck. I guess router.navigate() will also not work. Given that, I'm suspecting something is wrong in my design or code.

app.component-html

<app-page></app-page>
<router-outlet></router-outlet>

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { ContentComponent } from './content/content.component';

const routes = [
  { path: 'p/:permalink', component: ContentComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

page.component.html

<div *ngIf="allPages">
  <div *ngFor="let page of allPages | keyvalue">
    <a routerLink="{{ page.value['url'] }}"> {{ page.value['id']  }}</a>
  </div>
</div>

page.component.ts

import { Component, OnInit } from '@angular/core';

import { BloggerRestService } from '../blogger-rest.service';

@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.scss']
})
export class PageComponent implements OnInit {

  blogInfo = {
    "url" : "http://dkrypted.blogspot.com/"
  }

  allPages: any = null;

  constructor(
    private rest: BloggerRestService
  ) { }


  ngOnInit() {
    this.getPages();
  }

  getPages() {
    this.rest.getAllPages().subscribe( pages => {
      this.allPages = pages["items"];

      for( let page in this.allPages ) {
        let new_url = this.allPages[page]['url'].replace( this.blogInfo['url'], '/' );

        this.allPages[page]['url'] = new_url;
      }

      console.log(this.allPages);
    });
  }

  isEmptyObject( obj ) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
  }
}

content.component.html

<div *ngIf='post'>
  <p [innerHTML] = 'post["content"]'></p>
</div>

content.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { BloggerRestService } from '../blogger-rest.service';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.scss']
})
export class ContentComponent implements OnInit {

  blogInfo = {
    "url" : "http://dkrypted.blogspot.com/"
  }

  post: any;

  pageParam = {
    'permalink': ''
  }

  constructor(
    private route: ActivatedRoute,
    private rest: BloggerRestService,
    private router: Router
  ) { }

  ngOnInit() {
    this.pageParam['permalink'] = this.route.snapshot.paramMap.get('permalink');

    let path = "/p/" + this.pageParam['permalink'];
    this.getPage(path);
  }


  getPage( path ) {
    let allPages = null;
    let flag = false;

    this.rest.getAllPages().subscribe( pages => {
      allPages = pages["items"];

      console.log(allPages.length);

      if( allPages.length ) {
        for( let page in allPages ) {

          let new_url = allPages[page]['url'].replace( this.blogInfo['url'], '/' );

          if( new_url == path ) {
            flag = true;

            this.rest.getPage( allPages[page]['id'] ).subscribe((page: {}) => {
              this.post = page;
              console.log(this.post);
            });

            break;
          }
        }

        if( !flag )
            this.router.navigate(['/404']);
      }
    });

    console.log("Get Page called!");
  }

}

此处是指向Blogger API的链接,用于了解JSON结构 https://developers.google.com/blogger/docs/3.0/reference/pages

Here's the link to Blogger API for understanding the JSON structure https://developers.google.com/blogger/docs/3.0/reference/pages

我是Angular的新手,仍然在学习.我可能会错过一些东西.

I'm a newbie to Angular and still learning. It might be possible that I would've missed something.

推荐答案

更改路由时未更新的原因是,您正在使用paramMap的快照来获取permalink路由变量.相反,您应该使用ActivatedRoute.params observable.这样,当路线发生更改时,组件将知道它们并能够做出反应.

The reason it's not updating when you change the route is because you're using a snapshot of the paramMap to get the permalink route variable. Instead, you should use the ActivatedRoute.params observable. That way, when changes happen to the route, the component will know about them and be able to react.

this.route.params.pipe(
    switchMap(
        (params: Params) => {
            this.pageParam['permalink'] = params['permalink'];
            ...
        }
    )
)

这篇关于Router Link不会使用其他占位符加载另一个页面.这是正确的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆