代码之家  ›  专栏  ›  技术社区  ›  BJT

角度6-动态子路由

  •  1
  • BJT  · 技术社区  · 6 年前

    app-routing.module.ts程序

    import { NgModule } from '@angular/core';
    import { WeatherComponent } from './weather/weather.component';
    import { ForecastComponent } from './forecast/forecast.component';
    import { ForecastDailyComponent } from './forecast-daily/forecast-daily.component';
    import { ForecastResolverService } from './shared/services/resolvers/forecast-resolver.service';
    import { ForecastDailyResolverService } from './shared/services/resolvers/forecast-daily-resolver.service';
    
    import { RouterModule, Routes, PreloadAllModules } from '@angular/router';
    
    export const routes: Routes = [
      {
        path: '',
        component: WeatherComponent,
        pathMatch: 'full',
      },
      {
        path: ':name',
        component: ForecastComponent,
        resolve: {
          forecast: ForecastResolverService,
        },
        children: [
          {
            path: ':day',
            // i had here pathMatch: 'full', does not help
            component: ForecastDailyComponent,
            resolve: {
              forecast: ForecastDailyResolverService
            }
          }
        ]
      },
      {
        path: '**',
        redirectTo: '',
        pathMatch: 'full'
      }
    ];
    const ENABLE_TRACING = true;
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes, {
          enableTracing: ENABLE_TRACING,
          preloadingStrategy: PreloadAllModules,
        }),
      ],
      exports: [
        RouterModule
      ],
    })
    export class AppRoutingModule {}
    

    预测-分解器服务

    import { Injectable } from '@angular/core';
    import { ActivatedRouteSnapshot, RouterStateSnapshot, Resolve } from '@angular/router';
    
    import { WeatherForecastPayload } from '../../../shared/models/weather-forecast-payload.model';
    import { WeatherService } from '../../../shared/services/weather.service';
    import { CityService } from '../../../shared/services/city.service';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class ForecastResolverService implements Resolve<WeatherForecastPayload> {
    
      constructor(
        private weatherService: WeatherService,
        private cityService: CityService,
    
      ) { }
    
      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<WeatherForecastPayload> {
        const name = route.paramMap.get('name');
        const forecast = this.weatherService.getForecast(this.cityService.getCityID(name));
        return forecast;
      }
    }
    

    import { Injectable } from '@angular/core';
    import { ActivatedRouteSnapshot, RouterStateSnapshot, Resolve } from '@angular/router';
    
    import { WeatherForecast } from '../../models/weather-forecast.model';
    import { StoreService } from '../../services/store.service';
    import { WeatherForecastPayload } from '../../models/weather-forecast-payload.model';
    import { getWeekDayNumber } from '../../utils/converters';
    
    @Injectable()
    export class ForecastDailyResolverService implements Resolve<Array<WeatherForecast>> {
    
      constructor(
        private store: StoreService,
      ) { }
    
      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const day = route.paramMap.get('day');
    
        const forecast: WeatherForecastPayload = this.store.get('forecast');
    
        const dailyForecast = forecast.list.filter(
          (item) => {
            const forecastDay = getWeekDayNumber(String(new Date(item.dt_txt).getDay()));
            if (day === forecastDay) {
              return item;
            }
          }
        );
        return dailyForecast;
      }
    }
    

    气象组件

    <div class="jumbotron-fluid h-100 text-center m-0 d-flex flex-column justify-content-center">
      <div class="container-fluid h-100">
        <div class="row h-100">
          <div *ngFor="let weather of weatherList" class="col-lg m-4">
            <!-- weather.name ends up being London,Berlin or other city -->
            <app-weather-card [routerLink]="[weather.name]" [weather]="weather">
            </app-weather-card>
          </div>
        </div>
      </div>
    </div>
    

    预测.component.ts 链接到/:name/:day route

    <div class="jumbotron-fluid h-100 text-center m-0 d-flex flex-column justify-content-center">
      <div class="container-fluid h-100">
        <div class="row h-100">
          <div *ngFor="let dailyForecastList of forecastList" class="col-lg m-4">
            <app-forecast-card
              <!-- getDay() returns Mon or Thu or Fri etc. -->
              [routerLink]="[getDay(dailyForecastList.dt_txt)]"
              [forecast]="dailyForecastList">
            </app-forecast-card>
          </div>
        </div>
      </div>
    </div>
    <router-outlet></router-outlet>
    

    应用模块.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { AppComponent } from './app.component';
    import { SharedModule } from './shared';
    import { WeatherModule } from './weather/weather.module';
    import { ForecastModule } from './forecast/forecast.module';
    import { ForecastDailyModule } from './forecast-daily/forecast-daily.module';
    import { AppRoutingModule } from './app-routing.module';
    
    @NgModule({
      declarations: [
        AppComponent,
      ],
      imports: [
        SharedModule,
        BrowserModule,
        WeatherModule,
        ForecastModule,
        ForecastDailyModule,
        AppRoutingModule,
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { HttpClientModule } from '@angular/common/http';
    import { RouterModule } from '@angular/router';
    
    
    import { WeatherIconComponent } from './components/weather/weather-icon/weather-icon.component';
    import { WeatherTemperatureComponent } from './components/weather/weather-temperature/weather-temperature.component';
    import { WeatherCardComponent } from './components/weather/weather-card/weather-card.component';
    import { ForecastCardComponent } from './components/weather/forecast-card/forecast-card.component';
    import { NavigationComponent } from './components/navigation/navigation.component';
    import { FooterComponent } from './components/footer/footer.component';
    
    import { StoreService } from '../shared/services/store.service';
    
    
    @NgModule({
      imports: [
        CommonModule,
        FormsModule,
        RouterModule,
        ReactiveFormsModule,
        HttpClientModule,
      ],
      exports: [
        CommonModule,
        FormsModule,
        RouterModule,
        ReactiveFormsModule,
        HttpClientModule,
        WeatherIconComponent,
        WeatherTemperatureComponent,
        WeatherCardComponent,
        ForecastCardComponent,
        NavigationComponent,
        FooterComponent,
      ],
      declarations: [
        WeatherIconComponent,
        WeatherTemperatureComponent,
        WeatherCardComponent,
        ForecastCardComponent,
        NavigationComponent,
        FooterComponent,
      ],
      providers: [StoreService],
    })
    export class SharedModule {}
    

    存储服务

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable()
    export class StoreService {
    
      constructor() { }
    
      protected store$: Map<string, any> = new Map();
      public subject = new BehaviorSubject(this.store$);
    
      public get(key: any): any {
        return this.store$.get(key);
      }
    
      public set(key: any, value: any) {
        this.store$.set(key, value);
      }
    
    }
    

    在包含天气组件的入口路由“”上,您可以看到5个位置的天气列表,当单击其中一个位置时,路由器会将我们引导到/:name并行路由,在该路由中,您可以以行的形式查看未来5天的天气预报,单击其中一个位置会将我们引导到该天的每小时天气预报列表/:name/:day,但我可以从“:name”中看到内容,而且我希望只看到每小时的预测列表。

    谢谢。

    2 回复  |  直到 6 年前
        1
  •  3
  •   BJT    6 年前

    经过多次尝试和100个看到的例子(没有一个进入这个方向),我决定尝试这个路由器配置,它的工作,希望它对某人有帮助。

    import { NgModule } from '@angular/core';
    
    import { WeatherComponent } from './weather/weather.component';
    import { ForecastComponent } from './forecast/forecast.component';
    import { ForecastDailyComponent } from './forecast-daily/forecast-daily.component';
    import { ForecastResolverService } from './shared/services/resolvers/forecast-resolver.service';
    import { ForecastDailyResolverService } from './shared/services/resolvers/forecast-daily-resolver.service';
    
    import { RouterModule, Routes, PreloadAllModules } from '@angular/router';
    
    export const routes: Routes = [
      {
        path: '',
        component: WeatherComponent,
      },
      {
        path: ':name',
        component: ForecastComponent,
        resolve: {
          forecast: ForecastResolverService,
        }
      },
      {
        path: ':name/:day',
        component: ForecastDailyComponent,
        resolve: {
          forecast: ForecastDailyResolverService
        }
      },
      {
        path: '**',
        redirectTo: '',
        pathMatch: 'full'
      }
    ];
    
    const ENABLE_TRACING = false;
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes, {
          enableTracing: ENABLE_TRACING,
          preloadingStrategy: PreloadAllModules,
        }),
      ],
      exports: [
        RouterModule
      ],
    })
    export class AppRoutingModule {}
    
        2
  •  0
  •   BeetleJuice    6 年前

    由于ForecastComponent具有子路由,请确保此组件具有 <router-outlet> 在其自己的模板中,角度可以放置子路由