Угловой компонент не инициализируется из разрешения - PullRequest
0 голосов
/ 15 марта 2019

У меня есть приложение JHipster (Angular 5 + Spring Boot 2), и я пытаюсь создать новый маршрут для имеющегося у меня объекта модели (не созданного с помощью генератора сущностей, это просто простая модель). Проблема в том, что мой компонент не инициализируется, хотя я вижу, что приложение Angular вызывает правильный API и возвращает действительный ответ JSON.

Вот модель (упрощенная):

export interface IInstructor {
    id?: string;
}

export class Instructor implements IInstructor {
    constructor(
        public id?: string,
    ) {}
}

И служба, которая загружает Instructor объект:

type EntityResponseType = HttpResponse<IInstructor>;
@Injectable({ providedIn: 'root' })
export class InstructorService {
    public resourceUrl = SERVER_API_URL + 'api/instructor';
    constructor(private http: HttpClient) {}

    get(name: string): Observable<EntityResponseType> {
        return this.http.get<IInstructor>(`${this.resourceUrl}/${name}`, { observe: 'response' });
    }
}

И маршрут + разрешение:

@Injectable({ providedIn: 'root' })
export class InstructorResolve implements Resolve<IInstructor> {
    constructor(private service: InstructorService) {}

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const name = route.params['name'] ? route.params['name'] : null;
        if (name) {
            return this.service.get(name).pipe(map((instructor: HttpResponse<Instructor>) => instructor.body));
        }
        return of(new Instructor());
    }
}

export const instructorRoute: Routes = [
    {
        path: 'instructor/:name',
        component: InstructorComponent,
        resolve: {
            ride: InstructorResolve
        },
        data: {
            pageTitle: 'Instructor Details'
        }
    }
];

И, наконец, сам компонент и вид:

export class InstructorComponent implements OnInit {
    service: InstructorService;
    instructor: IInstructor;

    constructor(private instructorService: InstructorService,
                private activatedRoute: ActivatedRoute,
                private router: Router) {
        this.service = instructorService;
    }

    ngOnInit() {
        this.activatedRoute.data.subscribe(({ instructor }) => {
            this.instructor = instructor;
            console.log('Got instructor = ' + instructor);
        });
    }

<div id="jhi-instructor">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <hr/>
            <h2>Instructor Details</h2>
            <div *ngIf="instructor !== null">
                <h2>{{instructor.id}}</h2>
            </div>
        </div>
    </div>
</div>

Когда я перехожу на /instructor/somename, я вижу в отладчике Chrome, который выполняет XHR-вызов приложения с весенней загрузкой, и он возвращает действительную полезную нагрузку JSON. Но внутри InstructorComponent переменная instructor никогда не устанавливается. Я вижу консольное сообщение от ngOnInit, но объект, возвращаемый из activatedRoute, имеет значение null:

Got instructor = undefined instructor.component.ts:27:12
ERROR TypeError: "_co.instructor is undefined"
    View_InstructorComponent_1 InstructorComponent.html:1

Это шаблон, которому я следовал для других частей приложения (и в основном повторно использованный из автоматически сгенерированного кода JHipster), и он работал нормально, поэтому я не уверен, что мне не хватает.

Обновление

Как я и подозревал, это была человеческая ошибка. Я скопировал маршрут из другого компонента и не изменил значение разрешения (он использовал ride вместо instructor ). Большое спасибо за предложения!

resolve: {
    instructor: InstructorResolve
},

Ответы [ 2 ]

1 голос
/ 15 марта 2019

Попробуйте следующий код

export class InstructorComponent implements OnInit {
  service: InstructorService;
  instructor: IInstructor;

  constructor(private instructorService: InstructorService,
    private activatedRoute: ActivatedRoute,
    private router: Router) {
    this.service = instructorService;
  }

  ngOnInit() {
    this.activatedRoute.snapshot.data("ride").subscribe(({ instructor }) => {
      this.instructor = instructor;
      console.log('Got instructor = ' + instructor);
    });
  }
}
1 голос
/ 15 марта 2019

Полагаю, небольшая поправка, сделанная следующим образом, поможет получить нужные данные в компоненте.

const routes: Routes = [
{ path: 'instructor/:name',
    component: InstructorComponent,
    resolve: {
        ride: InstructorResolve
    },
    data: {
        pageTitle: 'Instructor Details'
    }
}]

А в компоненте внести изменения следующим образом.

export class InstructorComponent implements OnInit {
  service: InstructorService;
  instructor: IInstructor;

  constructor(private instructorService: InstructorService,
              private activatedRoute: ActivatedRoute,
              private router: Router) {
      this.instructor = this.route.snapshot.data["ride"];
      this.service = instructorService;
  }

}

Вам нужно извлечь данные, используя тот же ключ, который использовался для разрешения в части маршрутизации, в компоненте, чтобы получить разрешенные данные из маршрута.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...