Я пытаюсь загрузить страницу, напрямую вводя URL в браузере.У меня есть 3 компонента с именами BlogComponent, SideNavComponent и ContentComponent
Мои файлы выглядят следующим образом:
blog.component.ts
import {Component, OnDestroy, OnInit, ViewEncapsulation} from '@angular/core';
import {BlogService} from '../../../services/blog.service';
import {Subscription} from 'rxjs';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css'],
encapsulation: ViewEncapsulation.None
})
export class ContentComponent implements OnInit, OnDestroy {
pageContent: string;
blogContentSubscription: Subscription;
constructor(private blogService: BlogService, private http: HttpClient) {
}
ngOnInit() {
this.blogContentSubscription = this.blogService.selectedNode.subscribe((node) => {
console.log(node);
this.blogService.getPageContent(node).subscribe(data => {
}, (res: HttpErrorResponse) => {
this.pageContent = res.error.text;
});
});
}
ngOnDestroy(): void {
this.blogContentSubscription.unsubscribe();
}
}
sidenav.component.ts
import {Component, OnInit} from '@angular/core';
import {BlogService} from '../../../services/blog.service';
import {Router} from '@angular/router';
export interface Files {
name: string;
reference: string;
isExpanded: boolean;
children: Files[];
}
@Component({
selector: 'app-sidenav',
templateUrl: './sidenav.component.html',
styleUrls: ['./sidenav.component.css'],
})
export class SidenavComponent implements OnInit {
files: Files[];
selectedPath: string;
constructor(private blogService: BlogService, private router: Router) {
}
ngOnInit() {
this.blogService
.getTreeNodes()
.subscribe((files: []) => {
this.files = files;
});
}
toggleState(item: Files) {
item.isExpanded = !item.isExpanded;
}
nodeSelectEvent(reference: string, event: any) {
this.selectedPath = '';
this.selectedPath = reference;
this.getHierarchicalPath(event.target.parentElement.parentElement.parentElement);
this.router.navigate(['/blog/' + this.selectedPath]);
this.blogService.selectedNode.next(this.selectedPath);
}
getHierarchicalPath(element: Element) {
const parentReference = element.getAttribute('id');
if (parentReference) {
this.selectedPath = parentReference + '/' + this.selectedPath;
this.getHierarchicalPath(element.parentElement.parentElement);
}
}
}
content.component.ts
import {Component, OnDestroy, OnInit, ViewEncapsulation} from '@angular/core';
import {BlogService} from '../../../services/blog.service';
import {Subscription} from 'rxjs';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css'],
encapsulation: ViewEncapsulation.None
})
export class ContentComponent implements OnInit, OnDestroy {
pageContent: string;
blogContentSubscription: Subscription;
constructor(private blogService: BlogService, private http: HttpClient) {
}
ngOnInit() {
this.blogContentSubscription = this.blogService.selectedNode.subscribe((node) => {
console.log(node);
this.blogService.getPageContent(node).subscribe(data => {
}, (res: HttpErrorResponse) => {
this.pageContent = res.error.text;
});
});
}
ngOnDestroy(): void {
this.blogContentSubscription.unsubscribe();
}
}
и мой blog.service.ts
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
import {HttpClient} from '@angular/common/http';
@Injectable()
export class BlogService {
public selectedNode: Subject<string> = new Subject<string>();
public sideNavDisabled: Subject<boolean> = new Subject<boolean>();
constructor(private http: HttpClient) {
}
public getTreeNodes() {
return this.http.get('/assets/tree.json');
}
public getPageContent(page: string) {
return this.http.get('/assets/TreeStructure/' + page + '.html');
}
}
Теперь, всякий раз, когда я нажимаю на любой элемент в моем sidenav, иерархический путь этого элемента извлекается с использованием функции gethierarchicalPath в моих sidenav компонентах и передается в selectedNode субъекта в моем сервисе.Поскольку мой ContentComponent подписан на тему selectedNode .Я успешно могу использовать это значение и отобразить данные в шаблоне моего contentComponent.Я также формирую URL на основе иерархического пути и добавляю его к маршруту.Мой компонент блога также может обнаружить изменение URL-адреса и передать его selectedNode subject.
Проблема в том, что когда я перезагружаю страницу или пытаюсь загрузить URL-адрес напрямую, мойсодержимое не отображается на основе URL.Я попытался разместить console.log внутри метода подписки моего contentComponent.Но это не выполняется при перезагрузке страницы.
my app-routing.module.ts также выглядит следующим образом:
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {LoginComponent} from './modules/login/login.component';
import {BlogComponent} from './modules/blog/blog.component';
const routes: Routes = [
{
path: '',
redirectTo: 'blog',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
},
{
path: 'blog',
component: BlogComponent,
children: [
{
path: '**',
component: BlogComponent
}
]
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Мой полный код можно найти здесь - https://github.com/vibhorgoyal18/atest-blog
Пожалуйста, помогите мне решить эту проблему.