可以使用Rxjs的switchMap和toPromise方法将Promise转换为Observable。在路由中使用resolve来解决Promise并等待其结果。以下是一个示例:
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { switchMap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MyResolver implements Resolve {
constructor(private http: HttpClient) { }
resolve(): Observable {
return this.http.get('/api/data').pipe(
switchMap((data: any) => {
const promise = this.http.get('/api/otherdata').toPromise();
return Observable.fromPromise(promise).map((otherData: any) => {
data.otherData = otherData;
return data;
});
})
);
}
}
在路由中使用resolve:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MyResolver } from './my-resolver.service';
import { MyComponent } from './my.component';
const routes: Routes = [
{
path: 'details',
component: MyComponent,
resolve: {
data: MyResolver
}
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
providers: [MyResolver]
})
export class MyRoutingModule { }
这将在路由被访问之前执行MyResolver中的resolve方法,并等待Promise的结果,然后使用switchMap将其包装为一个Observable以便在MyComponent中使用。