无法在Angular 2中使用Resolve

时间:2018-01-24 13:53:11

标签: angular angular-routing

我想在视角以angular4渲染之前加载对象,所以我选择使用angular4的解析但我无法获取数据,不知道我做错了什么。

这是我的模块

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ActivatedRoute, Routes, RouterModule } from '@angular/router';
import { ResolverService } from './resolver.service';

export const routes: Routes = [
  { path: '', component: AppComponent, resolve: { transaction: ResolverService } }
];

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    RouterModule.forRoot(routes),
    BrowserModule,
    FormsModule
  ],
  providers: [ResolverService],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的解析器服务

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ResolverService implements Resolve<any> {
  constructor(private router: Router) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
    return new Observable(observer => {
      setTimeout(function () {
        observer.next(150)
      }, 1000);
    });
  }  
}

这是我的组件

import { Component, AfterViewInit, APP_INITIALIZER, InjectionToken, Inject } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot, ActivatedRoute } from '@angular/router';
import { student } from './sa-model.service';
import { Observable } from 'rxjs/Observable';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  constructor(private route: ActivatedRoute) {
  }

  ngAfterViewInit() {
    this.route.data.subscribe(success => {
      debugger;
      console.log(success);
    })
  }

}

但在组件中我期望得到我在解析器服务中传递的值150,但我没有得到任何值

任何人都可以指导我究竟做错了什么

2 个答案:

答案 0 :(得分:1)

这是因为你打开了observable但是在返回它之前从未完成它,所以没有任何东西被返回。加上这个:

setTimeout(function () {
  observer.next(150);
  observer.complete(); // Need to call complete once done.
}, 1000);

答案 1 :(得分:1)

使用take() ir first()

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
  return new Observable(observer => {
    setTimeout(function () {
      observer.next(150)
    }, 1000);
  }).take(1);
}  

你无法在路由器中传递开放的Observable