업데이트: Angular TitleStrategy 사용
7061 단어 webdevtypescriptangularseo
SEO 서비스 업데이트 중
다음과 같이 경로에
title
속성을 설정하는 것 외에는 아무것도 하지 않는 경우:// example route
const routes: Routes = [
{
path: 'details',
component: ContentDetailsComponent,
title: 'Details'
}
];
경로를 구축하고 검색하면 즉시 페이지 제목이 이어집니다. 이것은 우리가 원하는 것이 아니라 제어하려는 것입니다. 이때 재정의를 만들어야 합니다. 먼저 Google SEO project in StackBlitz을 다시 방문한 다음 유사한 작업을 담당하는 코드를 정리합니다.
루트
app.component
에는 라우팅 이벤트가 발생할 때마다 제목을 업데이트하는 이벤트 구독자가 있었습니다.// root app.component adaptation
export class AppComponent {
constructor(
//...
) {
// this is no longer needed since the TitleStrategy service
// already catches such events
/* this.router.events
.pipe(filter((e) => e instanceof NavigationEnd))
.subscribe((event) => {
let route = this.activatedRoute.snapshot;
while (route.firstChild) {
route = route.firstChild;
}
this.seoService.setPage((<any>route.data)?.title);
});
*/
}
}
다음으로
extends
TitleStrategy
를 포함하는 새 서비스를 만들어 보겠습니다. source code을 보면 buildTitle
가 예상대로 가장 깊은 경로 제목을 얻습니다.// /services/title.service.ts
@Injectable({ providedIn: 'root' })
export class AppTitleStrategy extends TitleStrategy {
constructor(private seoService: SeoService) {
super();
}
// override updateTitle which is similar to catching NavigationEnd
override updateTitle(routerState: RouterStateSnapshot) {
// this retrieves the title value of the deepest child in the route
const title = this.buildTitle(routerState);
// now set the title using Title service
// but we are going to use our previously created service: SeoService
this.seoService.setPage(title);
}
}
이를 사용하려면 루트 수준의 공급자 배열 또는 루트 라우팅 모듈에서 덮어써야 합니다.
// routing.module.ts
NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
// new: title strategy here
providers: [{ provide: TitleStrategy, useClass: AppTitleStrategy }],
})
export class AppRoutingModule {}
Twisting Angular Localization에서 유사한 리소스 기법을 어떻게 사용했는지 살펴보세요.
즐거운 코딩하세요. 🙂
Want to be updated of new articles on Sekrab Garage: Subscribe to Sekrab Parts newsletter
자원
관련 게시물
Reference
이 문제에 관하여(업데이트: Angular TitleStrategy 사용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/ayyash/update-using-angular-titlestrategy-3abb텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)