您好,登錄后才能下訂單哦!
要在Angular中創建自定義的路由解析器以在路由激活之前獲取數據,可以按照以下步驟進行操作:
resolve
方法來返回一個Observable對象,該對象會在路由激活之前獲取需要的數據。import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { DataService } from './data.service';
@Injectable()
export class CustomResolver implements Resolve<any> {
constructor(private dataService: DataService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
return this.dataService.getData();
}
}
RouterModule.forRoot
方法的providers
數組中添加該解析器。import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CustomResolver } from './custom-resolver.service';
const routes: Routes = [
{ path: 'example', component: ExampleComponent, resolve: { data: CustomResolver } }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
providers: [CustomResolver]
})
export class AppRoutingModule { }
data
屬性來獲取路由解析器返回的數據。import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent {
constructor(private route: ActivatedRoute) {
this.route.data.subscribe(data => {
console.log(data);
});
}
}
通過以上步驟,你就可以在Angular中創建自定義的路由解析器來在路由激活之前獲取數據了。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。