解析器在组件的ngoninit之后执行

时间:2018-06-29 17:10:06

标签: angular

我有以下组件,我正尝试使用解析器进行设置,因此数据应从解析器填充。但是,每当我运行该应用程序时,就没有数据了,使用调试器,ngoninit会在解析器中的断点之前被命中。也有数据,因为我可以在ngonint中订阅服务并取回数据,而无需使用解析器。

我的路线:

    export const appRoutes:Routes = [
    { path: 'application', component: ApplicationListComponent, resolve: {applications: ApplicationListResolver}},
    { path: '', redirectTo: '/application', pathMatch: 'full'}
];

我的解析器:

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { ApplicationService } from '../../service/application.service';

@Injectable()
export class ApplicationListResolver implements Resolve<any> {

  constructor(private _applicationService: ApplicationService) { }

  // Resolver automatically subscribes to an observable call that it gets
  resolve() {
    return this._applicationService.getApplications();
  }
}

我的组件:

import { IApplication } from './../entities/application.model';
import { ApplicationService } from './../service/application.service';
import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operator/map';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'oats-application-list',
  templateUrl: './application-list.component.html',
  styleUrls: ['./application-list.component.css']
})
export class ApplicationListComponent implements OnInit {
  applications: IApplication[];

  constructor(private route:ActivatedRoute) { }

  ngOnInit() {
    this.applications = this.route.snapshot.data['applications'];
   // this._applicationService.getApplications().subscribe((data:IApplication[]) => {
   //     this.applications = data;
   // });
  }

}

我的服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/RX';
import { catchError } from 'rxjs/operators';
import { IApplication } from '../entities/application.model';

@Injectable()
export class ApplicationService {

  constructor(private http: HttpClient) { }

  getApplications():Observable<IApplication[]>{
    return this.http.get<IApplication[]>('http://localhost/myapp/api/application')
      .pipe(catchError(this.handleError<IApplication[]>('getApplications', [])));
  }

    // operation is the method that triggered this, result the default value when there is error (optional)
    private handleError<T> (operation = 'operation', result?: T) {
      // function which takes an error of type any and returns an Observable of type T
      return (error: any): Observable<T> => {
        console.error(error);
        return Observable.of(result as T);  // return the result cast to type T
      }
    }  
}

解析器是否应该先命中然后才能命中?如果我从路由中删除路径“”,然后直接访问localhost:4200 /应用程序url,则会得到相同的结果。

1 个答案:

答案 0 :(得分:0)

我发现了问题,我没有路由器出口。