Angular 2 Resolve只能使用一次

时间:2017-02-07 14:54:16

标签: angular rxjs observable resolve resolver

我正在尝试制作一个返回用户的简单Resolve。但是,在我的应用程序中,我需要使用自己的类包装http组件,该类将Subject作为observable返回。 我的解析器在第一个用户链接上按预期工作,但在Resolve之后单击UserProfileComponent中的任何用户链接时,Resolve永远不会再次完成。我可以看到浏览器URL随新ID一起变化,以及UserResolve中的console.log打印,但没有任何反应。

我的路由器:

import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { UserProfileComponent } from './user-profile/user-profile.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './_resolve/guard.auth';
import { UserResolve } from './_resolve/user.resolve';

const appRoutes: Routes = [
  { path: '', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'user/:id', component: UserProfileComponent, canActivate: [AuthGuard], resolve: { user: UserResolve } },
  { path: 'login', component: LoginComponent },

  // otherwise redirect to home
  { path: '**', redirectTo: '' }
];

export const Routing = RouterModule.forRoot(appRoutes);

UserResolve:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { ApiService } from '../_services/api.service';
import { Observable } from 'rxjs';

import { User } from '../_models/user';

@Injectable()
export class UserResolve implements Resolve<User> {

  constructor(private apiService:ApiService) {}

  resolve(route: ActivatedRouteSnapshot):Observable<User> {
    console.log('getting user ' + route.params['id'] + ' with resolver');
    return this.apiService.getUser(route.params['id']).first();
  }
}

ApiService:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

import { RefreshHttpClient } from '../_injectables/refresh-http-client';
import { User } from '../_models/user';

@Injectable()
export class ApiService {

  constructor(private rfhttp:RefreshHttpClient) { }

  getUser(userId):Observable<User> {
    return this.rfhttp.get('/api/user?userId=' + userId);
  }

}

和RefreshHttpClient“获取”方法:

...
get(url):Observable<any> {
  var sub = new Subject<any>();
  var obs = this.http.get(url, {
    headers: this.createAuthorizationHeaders()
  })
  .map(res => res.json())
  .subscribe(
    data => {
      return sub.next(data);
    },
    error => {
      if (error.status == 401 || error.status == 403) {
        this.refreshAndRetry(() => {
          this.http.get(url, {
            headers: this.createAuthorizationHeaders()
          })
          .map(res => res.json())
          .subscribe(
            data => {
              return sub.next(data);
            },
            error => {
              console.error(error);
              return null;
            });
        });
      } else {
        console.error(error);
        return null;
      }
    }
  );

  return sub.asObservable();
}
...

编辑:添加UserProfileComponent:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { User } from '../_models/user';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.scss']
})
export class UserProfileComponent implements OnInit {

  abstract:Boolean;
  user:User;

  constructor(
    private route:ActivatedRoute
  ) { }

  ngOnInit() {
    this.user = this.route.snapshot.data['user']['data'];
    console.log(this.user);

...

请注意,我的API服务器返回一个带有“data”属性的JSON结构,因此['data']

此组件中的ngOnInit在除第一个之外的任何路线导航上都,这使我相信Resolver Observable永远不会完成。

1 个答案:

答案 0 :(得分:5)

问题可能在于您如何访问已解析的数据。

当URL更改时,如果要根据URL参数在组件本身内加载数据,则不会重新初始化组件,这就是您应该订阅路由参数更改的原因。

因此,当您访问已解析的数据时,您可能还应该考虑它可以在不重新初始化组件的情况下进行更改。

编辑:从UserProfileComponent代码可以看出我的假设很可能是正确的。尝试使用订阅读取解析数据:

this.route.data.subscribe(d => this.user = d['user']['data']);