У меня есть большое приложение AngularJS с пониженным приложением Angular 6 внутри.Если я перехожу непосредственно к приложению Angular, оно загружается правильно.Если я перехожу на домашнюю страницу AngularJS, а затем перехожу к URL-адресу Angular 6, компонент не загружается.Кроме того, после загрузки компонента Angular 6 он появляется на каждой странице приложения.
Мои настройки не совсем там.На самом деле я не могу найти никаких руководств по настройке маршрутизации в этом конкретном сценарии (кажется, все они предназначены для обновленной маршрутизации AngularJS).
Извините, я не могу получить рабочий пример - это сложная установка.
Угловой 6
app.module.ts
import { NgModule, Inject, ErrorHandler, ApplicationRef } from "@angular/core";
import { AngularFireModule } from "@angular/fire";
import { RouterModule, UrlHandlingStrategy } from "@angular/router";
import { HttpClientModule } from "@angular/common/http";
import { AngularFirestoreModule } from "@angular/fire/firestore";
import { BrowserModule } from "@angular/platform-browser";
import { UpgradeModule, downgradeComponent } from "@angular/upgrade/static";
import { NgbModule } from "@ng-bootstrap/ng-bootstrap";
import { CoreModule } from "../core/core.module";
import { WorkHelpModule } from "../work-help/work-help.module";
import { APP_CONFIG, AppConfig } from "./app.config";
import * as angular from "angular";
import moduleName from "../../app/scripts/app/app.module";
import { AirbrakeErrorHandler } from "../ErrorHandler";
import { AppComponent } from "./app.component";
import { StoreModule } from "@ngrx/store";
import { EffectsModule } from "@ngrx/effects";
import { reducers } from "../app/store";
export class Ng1Ng2UrlHandlingStrategy implements UrlHandlingStrategy {
shouldProcessUrl(url) {
console.log(
"shouldProcessUrl",
url.toString().startsWith("/work-help")
);
return url.toString().startsWith("/work-help");
}
extract(url) {
return url;
}
//@ts-ignore
merge(url, whole) {
return url;
}
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
UpgradeModule,
NgbModule,
HttpClientModule,
RouterModule.forRoot([]),
StoreModule.forRoot(reducers, {}),
EffectsModule.forRoot([]),
CoreModule,
WorkHelpModule,
AngularFirestoreModule,
AngularFireModule.initializeApp({ // deleted }),
],
entryComponents: [AppComponent],
providers: [
{ provide: ErrorHandler, useClass: AirbrakeErrorHandler },
{ provide: APP_CONFIG, useValue: AppConfig },
{ provide: UrlHandlingStrategy, useClass: Ng1Ng2UrlHandlingStrategy },
],
})
export class AppModule {
constructor(
private upgrade: UpgradeModule,
@Inject(APP_CONFIG) private config
) {}
ngDoBootstrap(app: ApplicationRef) {
angular
.module("config", [])
.constant("settings", this.config)
.constant("appName", "student");
angular.injector(["ng", "config"]).invoke([
"$http",
$http =>
$http({
method: "GET",
url: `${this.config.ENV.apiHost}/api/v2/roles`,
headers: { Accept: "application/vnd.api+json" },
})
.then(response => {
angular.module("config").constant("allRoles", response.data);
this.upgrade.bootstrap(document.documentElement, [moduleName], {
strictDi: true,
});
app.bootstrap(AppComponent);
})
.catch((/**response */) => {
// console.log(response); // uncomment if bootstrapping is failing
angular
.element("body")
.html(
`<h1 class="text-center color-red">We're sorry. There's been an error.</h1>`
);
}),
]);
}
}
angular
.module(moduleName)
.directive("appComponent", downgradeComponent({ component: AppComponent }));
app.component.ts
import { Component } from "@angular/core";
@Component({
selector: "app-component",
template: `
<div id="app-component">
<router-outlet></router-outlet>
</div>
`,
})
export class AppComponent {
constructor() {}
}
AngularJS
app.routes.js
export function appRoutes(
$stateProvider,
$urlRouterProvider,
$locationProvider
) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise("/");
$stateProvider
.state("student", {
abstract: true,
component: "app",
data: {
permissions: {
only: "hasValidSession",
redirectTo: "login",
},
},
resolve: {
student: ["Student", Student => Student.ready],
setPassword: [
"Student",
"student",
(Student, student) => {
if (!student.requireSetPassword || !!Student.spoofer) {
return true;
}
return Student.openSetPasswordModal();
},
],
},
redirectTo: "student.home",
})
.state("student.home", {
url: "/",
component: "home",
data: { pageTitle: "Home" },
});
}
appRoutes.$inject = [
"$stateProvider",
"$urlRouterProvider",
"$locationProvider",
];
index.html (выдержка)
<ui-view></ui-view>
<app-component></app-component>
work-help.routes.js
export function workHelpRoutes($stateProvider) {
$stateProvider
.state("student.workHelpOld", {
url: "/work-help-old",
component: "WorkHelp",
data: { pageTitle: "Work Help" },
resolve: {
student: ["student", student => student],
enrollment: [
"EnrollmentService",
EnrollmentService =>
EnrollmentService.get({
active: true,
include: "brand,course",
brandName: "Work Help",
}).$promise.then(response => response.enrollments.first()),
],
},
})
.state("student.workHelp", {
url: "/work-help",
data: { pageTitle: "Work Help" },
resolve: {},
});
}
workHelpRoutes.$inject = ["$stateProvider"];