Отсутствующий компонент в Angular, когда он имеет службу, упомянутую в конструкторе, не используется внутри самого компонента. Приложение JHipster
Вот что у нас есть в отладке браузера:
const Mp = {
pageTitle: "ученику"
}
, Ap = {
path: "to-student",
component: Fp,
data: Mp,
canActivate: [m.b]
};
class Dp {
constructor() {}
ngOnInit() {}
}
Интересно, что с
npm start
он скомпилирован хорошо и не работает во время выполнения только в том случае, если он собран с плагином npm из
maven
на производственной стороне (героку).
В модуле есть:
import {
BlogDocumentsComponent,
BlogFaqComponent,
BlogEntriesComponent,
ShopComponent,
ShopSuccessComponent,
ShopFailureComponent,
SyllablesComponent,
RedirectComponent,
// UsefulStuffComponent actually not there
} from './';
import 'd3';
import 'nvd3';
import { NvD3Module } from 'ng2-nvd3';
import { UsefulStuffComponent } from './useful-stuff/useful-stuff.component';
так
UsefulStuffComponent
не входит в общий импорт, но его путь правильный!
И это не упоминается в соответствующих
index.ts
модуля (он нам никогда не понадобится, если указан полный путь, правда?)
Таким образом, проблему можно решить, явно указав
UsefulStuffComponent
быть экспортированным в
index.ts
и экспортируется с другим компонентом таким же образом:
import {
BlogDocumentsComponent,
BlogFaqComponent,
BlogEntriesComponent,
ShopComponent,
ShopSuccessComponent,
ShopFailureComponent,
SyllablesComponent,
RedirectComponent,
UsefulStuffComponent actually not there
} from './';
import 'd3';
import 'nvd3';
import { NvD3Module } from 'ng2-nvd3';
// import { UsefulStuffComponent } from './useful-stuff/useful-stuff.component'; actually no import here
Итак, почему я получаю такой сбой во время выполнения, но никогда не получаю его
npm start
локально?
UPD:
Итак, по совету @Gaël Marziou я попытался локализовать изменение, которое привело к потере компонента в состоянии prod. Я обнаружил, что этот компонент по-прежнему вызывает ошибку prod:
import { Component, OnInit } from '@angular/core';
import { filter, map } from 'rxjs/operators';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { PaymentService } from 'app/businesslogic';
import { JhiAlertService } from 'ng-jhipster';
import { IAccessSubscription } from 'app/shared/model/access-subscription.model';
import { AccessSubscriptionService } from 'app/entities/access-subscription';
@Component({
templateUrl: './to-student.component.html',
styleUrls: ['./to-student.component.scss']
})
export class ToStudentComponent implements OnInit {
accessSubscriptions: IAccessSubscription[] = [];
accessSubscriptionsIds: number[] = [];
constructor(
protected jhiAlertService: JhiAlertService,
protected accessSubscriptionsService: AccessSubscriptionService,
protected paymentService: PaymentService
) {}
ngOnInit() {
this.loadAll();
}
loadAll() {
this.accessSubscriptionsService
.queryAllMine()
.pipe(
filter((mayBeOk: HttpResponse<IAccessSubscription[]>) => mayBeOk.ok),
map((response: HttpResponse<IAccessSubscription[]>) => response.body)
)
.subscribe(
(res: IAccessSubscription[]) => {
this.accessSubscriptions = res;
this.accessSubscriptions.map((item: IAccessSubscription) => {
this.accessSubscriptionsIds.push(item.id);
});
},
(res: HttpErrorResponse) => this.onError(res.message)
);
}
protected onError(errorMessage: string) {
this.jhiAlertService.error(errorMessage, null, null);
}
}
а этот уже хорошо работает:
import { Component, OnInit } from '@angular/core';
import { filter, map } from 'rxjs/operators';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { PaymentService } from 'app/businesslogic';
import { JhiAlertService } from 'ng-jhipster';
import { IAccessSubscription } from 'app/shared/model/access-subscription.model';
import { AccessSubscriptionService } from 'app/entities/access-subscription';
@Component({
templateUrl: './to-student.component.html',
styleUrls: ['./to-student.component.scss']
})
export class ToStudentComponent implements OnInit {
accessSubscriptions: IAccessSubscription[] = [];
accessSubscriptionsIds: number[] = [];
constructor(protected jhiAlertService: JhiAlertService, protected accessSubscriptionsService: AccessSubscriptionService) {}
ngOnInit() {
this.loadAll();
}
loadAll() {
this.accessSubscriptionsService
.queryAllMine()
.pipe(
filter((mayBeOk: HttpResponse<IAccessSubscription[]>) => mayBeOk.ok),
map((response: HttpResponse<IAccessSubscription[]>) => response.body)
)
.subscribe(
(res: IAccessSubscription[]) => {
this.accessSubscriptions = res;
this.accessSubscriptions.map((item: IAccessSubscription) => {
this.accessSubscriptionsIds.push(item.id);
});
},
(res: HttpErrorResponse) => this.onError(res.message)
);
}
protected onError(errorMessage: string) {
this.jhiAlertService.error(errorMessage, null, null);
}
}
Итак, нерабочий просто содержит импорт некоторой службы в конструкторе, которая никогда не использовалась:
protected paymentService: PaymentService
1 ответ
Некоторые ошибки Angular действительно сложно отладить, особенно если они не появляются в сборках разработчика.
Каждый раз, когда я сталкивался с такой ситуацией, я фактически откатывал свои изменения, пока не нашел фиксацию виновника.
Если вы делаете это после множества изменений, вы можете использовать скрипт с
git bisect
чтобы определить ошибочные строки, конечно, при условии, что ваши коммиты небольшие.
В идеале, чтобы избежать этого "археологического" поиска, вы должны установить автоматическую непрерывную интеграцию с самого начала вашего проекта, чтобы вы были уверены, что более глубокая проверка производственной сборки позволит выявить ошибки раньше.