업데이트: Angular TitleStrategy 사용

Angular 14는 TitleStrategy 루트에서 제공되는 새로운 서비스를 가져왔습니다. 이는 기본적으로 이전에 SEO in Angular: Static page titles using route data에서 수행한 작업을 수행합니다. 이제 제목을 경로의 직접적인 속성으로 설정할 수 있습니다. 이제 파헤쳐 서비스 스핀오프를 만드는 방법을 살펴보겠습니다.

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



자원


  • Angular TitleStrategy
  • StackBlitz project

  • 관련 게시물


  • Alternative way to localize in Angular
  • 좋은 웹페이지 즐겨찾기