无法使用角度7上的解析器预取数据

时间:2019-05-26 04:10:32

标签: angular spring-boot

我在预取API数据时遇到问题,但是我似乎没有正确。在获取数据之前,该路由仍处于激活状态。我正在尝试在angular 7中使用解析器服务来加载用户列表。

您在路由模块上有我的路由解析器:

`const routes: Routes = [
  {
    path: 'list', 
    component: ShowListComponent, 
    resolve: {personList: ResolverService}
  },
  {path: 'add', component: AddComponent},
  {path: 'edit', component: EditComponent},
  {path: 'edit/:id', component: EditComponent}
];`

这是我调用解析器的地方:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import {ServiceService} from '../../Service/service.service';
import { Person } from 'src/app/Model/Person';


@Component({
  selector: 'app-show-list',
  templateUrl: './show-list.component.html',
  styleUrls: ['./show-list.component.css']
})
export class ShowListComponent implements OnInit {

  persons:Person[];
  constructor(private service:ServiceService, private aRoute: ActivatedRoute ) { 

  }

  ngOnInit() {
    // Invoking resolver service
    this.persons = this.aRoute.snapshot.data['personList'];

  }
}

这是我的解析器服务:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Person } from '../Model/Person';
import { Observable} from 'rxjs';
import { ServiceService } from './service.service';


@Injectable({
  providedIn: 'root'
})
export class ResolverService implements Resolve<Person[]> {


  constructor(private _persons: ServiceService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Person[]> | Observable<never> {
    return this._persons.getPersons();      
  }
}

最后这是我的服务实现:

import { Injectable, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Person} from '../Model/Person';
import { identifierModuleUrl } from '@angular/compiler';


@Injectable({
  providedIn: 'root'
})
export class ServiceService  {

  persons: Person[];
  constructor(private http: HttpClient) { }


  List = 'http://localhost:8080/todoangular/persons';

  getPersons() {
    return this.http.get<Person[]>(this.List);
  } 
}

2 个答案:

答案 0 :(得分:0)

我认为正在发生的事情是您正在创建ResolverService的单例实例。因此,该服务仅创建一次,而在实例化之时处于ActivatedRouteSnapshot状态是什么状态。

看看Angular docs,您会发现它们仅使用Injectable()装饰了解析器(不提供In:'root')。然后,他们将ResolverService传递到模块的providers数组中。

答案 1 :(得分:0)

解析器未订阅已解析的Observable。

return this._persons.getPersons();是一个Observable,您必须手动订阅:

ngOnInit() {
  // Invoking resolver service
  this.aRoute.snapshot.data['personList'].subscribe(
    val => this.persons = val;
  );
}