zoukankan      html  css  js  c++  java
  • AngularJs 12 实现hash路由,并监听路由事件实现获取数据

    参考

    1. angular路由事件
    2. angular8教程(6)-路由复用策略
    3. angular中文网

    原因及问题

    1. 在使用默认的路由情况下, A(/) 页面进入B(/info)页面的时候,如果用浏览器从B返回到A,就会触发ngOnInit()方法,因为页面获取数据的方法放到了ngOnInit(),并且因为路由并没有显式的显示在地址栏,A页面会触发ngOnInit()方法,并且A页面的分页数据会重置到第一页。
    2. 尝试分页get参数放到url中,再使用 window.location.hash.search 方法去获取get参数,总是获取不准确。。
    3. 尝试把翻页数据使用 this.router.navigateByUrl("/?page=" + (this.pageNum + 1)); 方法把get参数放到url中,再window.location.href跳转,这样就能实现A返回B 实现A留在进入B页面的页数。但是问题是,每次跳转都会加载一些静态文件,失去了单页应用的意义。。。(后面发现使用this.activatedRoute.snapshot.queryParams可以比较方便的获取url中的参数,解决了这次遇到的问题)

    注意事项

    我使用的编辑器是VS Code,通过插件实现自动生成页面 ,他有时候不会自动的把生成创建的Service、Component等自动引入到app.module.ts中去,就会导致虽然可以访问,但是页面上的一些自定义标签或者form表单报错,如:该属性不存在于该标签,因为他不是input标签。所以需要你在创建页面或者文件的时候,最好去app.module.ts中检查一下,防止没有自动引入而导致页面奇怪的错误

    image

    代码

    1. 开启hash路由,app.module.ts 的 providers 数组添加 Location, {provide: LocationStrategy, useClass: HashLocationStrategy}, 示例如下,设置完之后刷新页面就会看到url后面追加了#
    import { NgModule } from '@angular/core';
    // 公共组件调用
    import { BrowserModule } from '@angular/platform-browser';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { HttpClientModule } from '@angular/common/http';
    import { HashLocationStrategy, Location, LocationStrategy } from '@angular/common';
    // 公共services
    import { RequestService } from './services/request.service';
    
    @NgModule({
      declarations: [
        AppComponent,
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
      ],
      providers: [
        // hash路由
        Location, 
        {provide: LocationStrategy, useClass: HashLocationStrategy},
        //
        RequestService,
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    
    1. component(你的页面),构造函数 constructor() 中监听 路由事件
        this.router.events.pipe(
          filter(e => e instanceof NavigationEnd)
        ).subscribe(e => {
          // 获取页面数据的地方,调用你页面获取数据的方法
          this.onGetArticles();
        });
    

    完整的页面代码参考

    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute ,NavigationEnd} from '@angular/router'; //导入router服务
    import { HomeArticleService } from '../../services/home-article.service';
    import { ArticleType } from '../../types/article-type';
    import { topFunction } from '../../plugin/function';
    import {map,filter} from 'rxjs/operators';
    import { Subscription } from 'rxjs';
    
    @Component({
      selector: 'app-home-article-list',
      templateUrl: './home-article-list.component.html',
      styleUrls: ['./home-article-list.component.scss']
    })
    export class HomeArticleListComponent implements OnInit {
    
      public articles?: ArticleType[]; //PagehelperType<ArticleType>
      public isFirstPage?: boolean; // 是第一页?
      public isLastPage?: boolean; // 是最后一页
      public pages?: number; // 页面数量
      public pageNum = 1; // 当前页数
      // 退订路由可观察对象
      public subscription?:Subscription;
    
      constructor(protected router: Router, private activatedRoute: ActivatedRoute, protected homeArticleService: HomeArticleService) { 
        
      }
    
      ngOnInit() {
        // 初始化页面加载数据(第一次进入页面)
        this.onGetArticles();
        // 路由切换加载数据
        this.subscription = this.router.events.pipe(
          filter(e => e instanceof NavigationEnd)
        ).subscribe(e => {
          // 获取数据
          this.onGetArticles();
        });
      }
      ngOnDestroy(){
        this.subscription && this.subscription.unsubscribe();
      }
      /**
       * 获取文章列表
       */
      onGetArticles() {
        // 获取url中的get参数
        let pageNum = this.activatedRoute.snapshot.queryParams.page;
        pageNum = pageNum < 1? 1 : pageNum;
        this.homeArticleService.getArticles(pageNum).then(res => {
          this.articles = res.data.list;
          this.isFirstPage = res.data.isFirstPage;
          this.isLastPage = res.data.isLastPage;
          this.pages = res.data.pages;
          this.pageNum = res.data.pageNum;
        });
      }
      /**
       * 跳转文章详情
       * @param id 
       */
      onShowInfo(id: number) {
        this.router.navigateByUrl('article/' + id);
      }
      /**
       * 翻页
       */
      prePage() {
        // 返回顶部
        topFunction();
        this.router.navigateByUrl("/?page=" + (this.pageNum - 1));
      }
      /**
       * 翻页
       */
      nextPage() {
        // 返回顶部
        topFunction();
        this.router.navigateByUrl("/?page=" + (this.pageNum + 1));
      }
    
    }
    
    如果觉得文章对您有帮助,希望您能 关注+推荐 哦
  • 相关阅读:
    〖Linux〗Kubuntu设置打开应用时就只在打开时的工作区显示
    〖Linux〗Kubuntu, the application 'Google Chrome' has requested to open the wallet 'kdewallet'解决方法
    unity, dll is not allowed to be included or could not be found
    android check box 自定义图片
    unity, ios skin crash
    unity, Collider2D.bounds的一个坑
    unity, ContentSizeFitter立即生效
    类里的通用成员函数应声明为static
    unity, Gizmos.DrawMesh一个坑
    直线切割凹多边形
  • 原文地址:https://www.cnblogs.com/xiaqiuchu/p/15157888.html
Copyright © 2011-2022 走看看