ResolveData
此示例將向你展示如何在呈現應用程式檢視之前解析從服務獲取的資料。
在撰寫本文時使用 angular / router 3.0.0-beta.2
users.service.ts
...
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { User } from './user.ts';
@Injectable()
export class UsersService {
constructor(public http:Http) {}
/**
* Returns all users
* @returns {Observable<User[]>}
*/
index():Observable<User[]> {
return this.http.get('http://mywebsite.com/api/v1/users')
.map((res:Response) => res.json());
}
/**
* Returns a user by ID
* @param id
* @returns {Observable<User>}
*/
get(id:number|string):Observable<User> {
return this.http.get('http://mywebsite.com/api/v1/users/' + id)
.map((res:Response) => res.json());
}
}
users.resolver.ts
...
import { UsersService } from './users.service.ts';
import { Observable } from 'rxjs/Rx';
import {
Resolve,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from "@angular/router";
@Injectable()
export class UsersResolver implements Resolve<User[] | User> {
// Inject UsersService into the resolver
constructor(private service:UsersService) {}
resolve(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<User[] | User> {
// If userId param exists in current URL, return a single user, else return all users
// Uses brackets notation to access `id` to suppress editor warning, may use dot notation if you create an interface extending ActivatedRoute with an optional id? attribute
if (route.params['id']) return this.service.get(route.params['id']);
return this.service.index();
}
}
users.component.ts
這是一個包含所有使用者列表的頁面元件。它對使用者詳細資訊頁面元件的工作方式類似,將 data.users
替換為 data.user
或 app.routes.ts 中定義的任何鍵 (見下文)
...
import { ActivatedRoute} from "@angular/router";
@Component(...)
export class UsersComponent {
users:User[];
constructor(route: ActivatedRoute) {
route.data.subscribe(data => {
// data['Match key defined in RouterConfig, see below']
this.users = data.users;
});
}
/**
* It is not required to unsubscribe from the resolver as Angular's HTTP
* automatically completes the subscription when data is received from the server
*/
}
app.routes.ts
...
import { UsersResolver } from './resolvers/users.resolver';
export const routes:RouterConfig = <RouterConfig>[
...
{
path: 'user/:id',
component: UserComponent,
resolve: {
// hence data.user in UserComponent
user: UsersResolver
}
},
{
path: 'users',
component: UsersComponent,
resolve: {
// hence data.users in UsersComponent, note the pluralisation
users: UsersResolver
}
},
...
]
...
app.resolver.ts
可選擇將多個解析器繫結在一起。
重要提示: 必須首先匯入解析器中使用的服務,否則你將收到無解決方案錯誤提示。請記住,這些服務將在全域性範圍內提供,你無需再在任何元件的 providers
中宣告它們。請務必取消訂閱任何訂閱以防止記憶體洩漏
...
import { UsersService } from './users.service';
import { UsersResolver } from './users.resolver';
export const ROUTE_RESOLVERS = [
...,
UsersService,
UsersResolver
]
main.browser.ts
在自舉期間必須注入旋轉變壓器。
...
import {bootstrap} from '@angular/platform-browser-dynamic';
import { ROUTE_RESOLVERS } from './app.resolver';
bootstrap(<Type>App, [
...
...ROUTE_RESOLVERS
])
.catch(err => console.error(err));