【问题标题】:Angular Navigation Strategy角度导航策略
【发布时间】:2018-09-27 11:31:27
【问题描述】:

我正在构建一个有角度的应用程序,但我的 html 结构有点不同,我有多用途模板,所以用户可以在这些页面之间导航,而不是单页,它们都堆叠在一起。我有 3 个组件:

  • 主页组件
  • 关于组件
  • NavbarComponent - 带有 2 个锚标签可向下滚动到目标部分

模板导航栏组件:

<div>
    <a href="#home">Home</a>
    <a href="#about">About</a>
</div>

模板主页组件:

<div>
    <h1>Home</h1>
    lorem...
</div>

模板关于组件:

<div>
    <h1>About</h1>
    lorem...
</div>

模板应用组件:

<navbar></navbar>
<home id="home"></home>
<about id="about"></about>

here's the demo

所以我的问题是当用户单击链接时,我的问题不是 myapp.com/#home 或 myapp.com/#about,我怎样才能获得该格式的 url:myapp.com/home 基于我在 app.component.html 中的模板结构,我将根据 url 将窗口向下滚动到目标部分,但我需要知道如何更改行为,因为如果我这样做:

<a href="/home">Home</a>

浏览器会发出 GET 请求

【问题讨论】:

    标签: javascript angular angular6 angular-router


    【解决方案1】:

    所以我的问题是当用户单击链接时,我的问题不是 myapp.com/#home 或 myapp.com/#about,我如何才能获得该格式的 url:myapp.com/home

    我刚刚为你做了一个超小的示例项目。它提供了您想要的功能。

    这里是演示:https://codesandbox.io/s/xj8pvl18lq

    1。在 app.module.ts 中,我们将有这样的内容:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { AppComponent } from './app.component';
    import { HomeComponent } from './components/home.component';
    import { AboutComponent } from './components/about.component';
    
    const appRoutes: Routes = [
      { path: '', component: HomeComponent },
      { path: 'about', component: AboutComponent }
    ];
    
    @NgModule({
      declarations: [AppComponent, AboutComponent, HomeComponent],
      imports: [BrowserModule, RouterModule.forRoot(appRoutes)],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule {}

    2。在app.component.ts 中,我们有:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>
          <a routerLink="/">Home</a>
          <a routerLink="/about">About</a>
          <hr/>
          <router-outlet></router-outlet>
        </div>
      `
    })
    export class AppComponent {}

    3。这是两个超级简单的组件:Home 组件和 About 组件

    home.component.ts

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-home',
      template: `
            <div>
                <h2>Home</h2>
            </div>
        `
    })
    export class HomeComponent {}

    about.component.ts

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-about',
      template: `
            <div>
                <h2>About</h2>
            </div>
        `
    })
    export class AboutComponent {}

    试一试,希望它能如你所愿。

    【讨论】:

    • 您提供了一个工作示例,但没有解释这如何解决他的问题。
    • 谢谢,举个例子,但在我的例子中,我有一个不同的模板,我使用的是一个多用途模板,这意味着用户不会在页面之间导航
    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多