Можно ли использовать модуль маршрутизации для вызова функций, которые считывают текущее значение маршрутизации? - PullRequest
0 голосов
/ 03 февраля 2020

Вкл. Angular Я хотел бы вызвать некоторые функции, которые будут возвращать значение в соответствии с текущей страницей маршрутизации. Теперь некоторые функции временно размещены в элементе, который мне нужно изменить с помощью компонента маршрута.

Я знаю, чтобы кодировать эти функции. Мои вопросы: 1. Нужно ли мне создавать сервис, такой как «ColorService» для этих функций? 2. Должен ли я вызывать эти функции из компонентов, которые я хотел бы изменить в соответствии с маршрутизацией? или из модуля маршрутизации?

Это мой текущий модуль маршрутизации:

import { NgModule } from '@angular/core';
import { HomeHebComponent } from '../components/home-heb/home-heb.component';
import { AboutHebComponent } from '../components/about-heb/about-heb.component';
import { ContactHebComponent } from '../components/contact-heb/contact-heb.component';
import { GalleryComponent } from '../components/gallery/gallery.component';
import { Routes, RouterModule } from '@angular/router';
import { Page404Component } from '../components/page404/page404.component';
import { PlywoodHebComponent } from '../components/plywood-heb/plywood-heb.component';
import { MdfHebComponent } from '../components/mdf-heb/mdf-heb.component';
import { TegoTlatOsbHebComponent } from '../components/tego-tlat-osb-heb/tego-tlat-osb-heb.component';
import { HardwoodHebComponent } from '../components/hardwood-heb/hardwood-heb.component';
import { MapHebComponent } from '../components/map-heb/map-heb.component';

const routes: Routes = [
    { path: 'heb/home', component: HomeHebComponent},
    { path: 'heb/about', component: AboutHebComponent},
    { path: 'heb/plywood1', component: PlywoodHebComponent},
    { path: 'heb/mdf', component: MdfHebComponent},
    { path: 'heb/hardwood', component: HardwoodHebComponent},
    { path: 'heb/plywood2', component: TegoTlatOsbHebComponent},
    { path: 'heb/contact', component: ContactHebComponent},
    { path: 'heb/map', component: MapHebComponent},
    { path: 'heb/gallery', component: GalleryComponent},
    { path: '', redirectTo: '/heb/home', pathMatch: 'full' },
    { path: '**', component: Page404Component }

];


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

Это пример функции изменения цвета для файла меню:

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

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {
    private route: string;
  constructor(location: Location, private router: Router) {
      router.events.subscribe( val => {
          if (location.path() !== '') {
              this.route = location.path();
              console.log(this.route);

      } else {
          this.route = 'home';
          console.log(this.route);

      }
    });
   }

  ngOnInit() {

  }
// switches color according to routing
  private  toggleColorAboutRouting(): string {
      return this.route === '/heb/about' ?  'white' :  'initial';
  }
}


Ответы [ 2 ]

0 голосов
/ 03 февраля 2020

вы можете передать объект данных на маршрут

{ path: 'heb/about', component: AboutHebComponent, data: {color: 'white'}},

, и он станет:

import { NgModule } from '@angular/core';
import { HomeHebComponent } from '../components/home-heb/home-heb.component';
import { AboutHebComponent } from '../components/about-heb/about-heb.component';
import { ContactHebComponent } from '../components/contact-heb/contact-heb.component';
import { GalleryComponent } from '../components/gallery/gallery.component';
import { Routes, RouterModule } from '@angular/router';
import { Page404Component } from '../components/page404/page404.component';
import { PlywoodHebComponent } from '../components/plywood-heb/plywood-heb.component';
import { MdfHebComponent } from '../components/mdf-heb/mdf-heb.component';
import { TegoTlatOsbHebComponent } from '../components/tego-tlat-osb-heb/tego-tlat-osb-heb.component';
import { HardwoodHebComponent } from '../components/hardwood-heb/hardwood-heb.component';
import { MapHebComponent } from '../components/map-heb/map-heb.component';

const routes: Routes = [
    { path: 'heb/home', component: HomeHebComponent},
    { path: 'heb/about', component: AboutHebComponent, data: {color: 'white'}},
    { path: 'heb/plywood1', component: PlywoodHebComponent},
    { path: 'heb/mdf', component: MdfHebComponent},
    { path: 'heb/hardwood', component: HardwoodHebComponent},
    { path: 'heb/plywood2', component: TegoTlatOsbHebComponent},
    { path: 'heb/contact', component: ContactHebComponent},
    { path: 'heb/map', component: MapHebComponent},
    { path: 'heb/gallery', component: GalleryComponent},
    { path: '', redirectTo: '/heb/home', pathMatch: 'full' },
    { path: '**', component: Page404Component }

];


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

, а в вашем компоненте вы можете получить доступ к данным с помощью ActivatedRoute

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

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
color = 'initial';
export class MenuComponent implements OnInit {
    private route: string;
  constructor(location: Location, private router: Router, private route: ActivatedRoute,) {
     route.data.subscribe(
       (data)=> this.color = data.color);

}

в примере я просто установил значение переменной color Отредактировано.

0 голосов
/ 03 февраля 2020

Вы можете использовать Angular Router и проверить свойство url, чтобы задействовать эту функциональность в вашем компоненте.

export class MenuComponent implements OnInit {
  private route: string;

  constructor(router: Router) {}

  ngOnInit() {
      this.route = this.toggleColorAboutRouting(this.router.url);
  }

// switches color according to routing
  private  toggleColorAboutRouting(url: string): string {
      return this.route === '/heb/about' ?  'white' :  'initial';
  }
}
...