在Angular应用程序之外访问Angular路由数据可以通过以下步骤实现:
@Injectable
装饰器来定义一个服务,并在该服务中定义一个可观察对象(Observable)来存储路由数据。import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RouteDataService {
private routeDataSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
public routeData$: Observable<any> = this.routeDataSubject.asObservable();
constructor() { }
public setRouteData(data: any): void {
this.routeDataSubject.next(data);
}
public getRouteData(): Observable<any> {
return this.routeData$;
}
}
data
属性来定义需要共享的路由数据。import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent, data: { title: 'Home' } },
{ path: 'about', component: AboutComponent, data: { title: 'About' } },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
import { Component, OnInit } from '@angular/core';
import { RouteDataService } from './route-data.service';
@Component({
selector: 'app-about',
template: `
<h1>About</h1>
<p>{{ routeData }}</p>
`
})
export class AboutComponent implements OnInit {
public routeData: any;
constructor(private routeDataService: RouteDataService) { }
ngOnInit() {
this.routeDataService.getRouteData().subscribe(data => {
this.routeData = data;
});
}
}
通过以上步骤,我们可以在Angular应用程序之外访问Angular路由数据。在需要共享路由数据的地方,可以调用setRouteData()
方法来更新路由数据,在需要访问路由数据的地方,可以调用getRouteData()
方法来获取最新的路由数据。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云