Angular의 경로를 기반으로 메타 설명을 동적으로 추가합니다.
저는 Angular 5를 사용하여 작은 브로셔 형태의 웹사이트를 만들고 있습니다.지금까지 제 경로를 설정해 두었고, 활성화된 경로에 따라 페이지 제목이 동적으로 바뀝니다.저는 이 블로그의 지침을 사용하여 이 작업을 수행하게 되었습니다. https://toddmotto.com/dynamic-page-titles-angular-2-router-events
현재 app.module.ts에 다음과 같이 경로와 제목을 저장하고 있습니다.
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: '',
component: HomeComponent,
data: {
title: 'Home'
}
},
{
path: 'about',
component: AboutComponent,
data: {
title: 'About'
}
},
{
path: 'products-and-services',
component: ProductsServicesComponent,
data: {
title: 'Products & Services'
}
},
{
path: 'world-class-laundry',
component: LaundryComponent,
data: {
title: 'World Class Laundry'
}
},
{
path: 'contact',
component: ContactComponent,
data: {
title: 'Contact'
}
},
{
path: '**',
component: NotFoundComponent,
data: {
title: 'Page Not Found'
}
}
])
],
아래에 메타 설명을 추가하면 거기에도 저장하고 싶습니다.data:
충분히 쉬울 겁니다.
위 블로그 링크에 나와 있는 다음 코드로 제목 데이터를 끌어 올립니다.
ngOnInit() {
this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map((route) => {
while (route.firstChild) route = route.firstChild;
return route;
})
.filter((route) => route.outlet === 'primary')
.mergeMap((route) => route.data)
.subscribe((event) => {
this.titleService.setTitle(event['title']);
});
}
그래서 제 질문은 메타 설명을 같은 방법으로 동적으로 설정할 수 있는 방법이 있을까요.페이지 제목과 메타 설명 기능을 결합할 수 있는 방법이 있다면 이상적일 것입니다.
제가 Angular training이 매우 제한적이라 초보적인 질문일 수도 있습니다.저는 디자이너/css/html 같은 사람에 가깝습니다.
먼저 다음과 같은 SEO 서비스 또는 Something을 만듭니다.
import {Injectable} from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
@Injectable({
provideIn: 'root' // Add this to ensure your SEO service will be app-wide available
})
export class SEOService {
constructor(private title: Title, private meta: Meta) { }
updateTitle(title: string) {
this.title.setTitle(title);
}
updateOgUrl(url: string) {
this.meta.updateTag({ name: 'og:url', content: url })
}
updateDescription(desc: string) {
this.meta.updateTag({ name: 'description', content: desc })
}
}
구성 요소에 SEO 서비스를 주입한 후(app.component.ts가 좋음) OnInit 메서드에서 메타 태그와 제목을 설정합니다.
ngOnInit() {
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route) => {
while (route.firstChild) route = route.firstChild;
return route;
}),
filter((route) => route.outlet === 'primary'),
mergeMap((route) => route.data)
)
.subscribe((event) => {
this._seoService.updateTitle(event['title']);
this._seoService.updateOgUrl(event['ogUrl']);
//Updating Description tag dynamically with title
this._seoService.updateDescription(event['title'] + event['description'])
});
}
그런 다음 경로를 다음과 같이 구성합니다.
{
path: 'about',
component: AboutComponent,
data: {
title: 'About',
description:'Description Meta Tag Content',
ogUrl: 'your og url'
}
},
이것은 메타태그를 다루는 명확한 방법입니다.페이스북과 트위터 특정 태그를 더 쉽게 업데이트할 수 있습니다.
경로 변경 시 동적으로 설정된 제목을 위한 Angular 6+ 및 RxJS 6+ 솔루션
Angular 6으로 업그레이드할 경우 이를 해결할 수 있습니다.
이 서비스는 다음과 같습니다.
- 경로변경시메타제목을업데이트합니다.
- 원하는 모든 이유로 제목을 재정의하는 옵션입니다.
SEO/메타 서비스를 다음과 같이 생성/변경합니다.
import { Injectable } from '@angular/core';
import { Title, Meta } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { filter, map, mergeMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class MetaService {
constructor(
private titleService: Title,
private meta: Meta,
private router: Router,
private activatedRoute: ActivatedRoute
) { }
updateMetaInfo(content, author, category) {
this.meta.updateTag({ name: 'description', content: content });
this.meta.updateTag({ name: 'author', content: author });
this.meta.updateTag({ name: 'keywords', content: category });
}
updateTitle(title?: string) {
if (!title) {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route) => {
while (route.firstChild) { route = route.firstChild; }
return route;
}),
filter((route) => route.outlet === 'primary'),
mergeMap((route) => route.data)).subscribe((event) => {
this.titleService.setTitle(event['title'] + ' | Site name');
});
} else {
this.titleService.setTitle(title + ' | Site name');
}
}
}
서비스를 가져와 컨스트럭터에 호출합니다.
app.component.ts
constructor(private meta: MetaService) {
this.meta.updateTitle();
}
그리고 이것은 여전히 이와 같은 경로를 포맷해야 합니다.
경로 file.ts
{
path: 'about',
component: AboutComponent,
data: {
title: 'About',
description:'Description Meta Tag Content'
}
},
Angular 6에서 제목/메타를 동적으로 업데이트하려는 사용자와 다른 사용자에게 도움이 되기를 바랍니다.
Title
Angular 4에서 소개된 프로바이더로 서버와 클라이언트 모두에서 이 작업을 수행해야 합니다.
작성 또는 업데이트 방법title
꼬리표와description
메타 태그, 다음과 같습니다.
import { Meta, Title } from '@angular/platform-browser';
...
constructor(public meta: Meta, public title: Title, ...) { ... }
...
this.meta.updateTag({ name: 'description', content: description });
this.title.setTitle(title);
Angular 페이지는 클라이언트 측에서 렌더링되므로 크롤러가 메타 태그를 검출할 수 없습니다.대부분의 크롤러는 동적 메타태그가 탐지되지 않아 런타임에 자바스크립트를 실행하지 않습니다.이것은 페이스북과 트위터에도 해당됩니다.
서버 사이드 렌더링 또는 사전 렌더링 서비스(예: prerender.io )를 위해 Angular Universal을 사용해야 합니다.
편집:- 나는 이것을 위한 좋은 유튜브 튜토리얼을 발견했습니다.다음은 https://www.youtube.com/watch?v=lncsmB5yfzE 링크입니다.
Routes 배열에서 데이터(타이틀, 설명 등)를 사용하는 IMO는 일관성이 없어 모든 데이터를 한 곳에 모을 수 있습니다.또한 2021년에는 일반적인 Angular 툴을 즉시 사용할 수 있습니다.
서측 지도
export const seoSitemap: ISitemapTag[] = [
{ customUrl: '/contact', title: null, description: 'Some description there', image: '/assets/path/to/image' },
{ customUrl: '/about', title: 'custom about title', description: 'Some description about', image: '/assets/path/to/another-image' }
];
export interface ISitemapTag {
customUrl: string;
title: string | null;
description: string | null;
image: string | null;
}
메타태그.service.ts:
import { Injectable } from '@angular/core';
import { Meta, MetaDefinition, Title } from '@angular/platform-browser';
@Injectable()
export class MetatagsService {
constructor(private title: Title, private meta: Meta) {}
updateTitle(title: string) {
this.title.setTitle(title);
}
updateTag(tag: MetaDefinition) {
this.meta.updateTag(tag);
}
updateTags(tags: Array<MetaDefinition | null>) {
tags.forEach((tag) => {
tag && this.meta.updateTag(tag);
});
}
}
app.component.ts
import { MetatagsService } from './shared/services/metatags.service';
import { seoSitemap } from './seoSitemap';
constructor() {
this.sub = this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
this.setMetaTags(event);
}
});
}
ngOnDestroy() { this.sub && this.sub.unsubscribe() }
private setMetaTags(event: NavigationEnd) {
const item = seoSitemap.find((i) => event.urlAfterRedirects === i.customUrl);
if (item) {
if (item.title) this.metatagsService.updateTitle(item.title);
this.metatagsService.updateTags([
item.description ? { name: 'description', content: item.description } : null,
item.image ? { name: 'image', content: item.image } : null,
]);
this.metatagsService.updateTag({ property: 'og:url', content: window.location.href });
} else {
this.metatagsService.updateTitle('Common title there');
}
}
제 프로젝트와 관련된 부분입니다. (각도 2/4)
app-routing.module.ts:
경로:
... const appRoutes: Routes = [
{
path: 'path1', loadChildren: './path1#path1Module',
data: {
title: '...',
description: '...',
keywords: '...'
}
},
{
path: 'path2', loadChildren: './path2#path2Module',
data: {
title: '...',
description: '...',
keywords: '...'
}
} ...
app.component.ts(또는 부트스트랩 구성 요소):
가져오기:
// imports
import { Component, OnInit} from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { Title,Meta } from '@angular/platform-browser';
생성자:
// constructor:
constructor(private router: Router,
private route: ActivatedRoute,
private titleService: Title, private meta: Meta) {}
ngOnInit() 메서드:
ngOnInit() {
this.router.events
.filter((event) => event instanceof NavigationEnd)
.map(() => this.route)
.map((route) => {
while (route.firstChild) route = route.firstChild;
return route;
})
.filter((route) => route.outlet === 'primary')
.mergeMap((route) => route.data)
.subscribe((event) => {
this.updateDescription(event['description'], event['keywords'], event['title']);
});
}
ngOnInit()에서 호출된 제목 및 메타 태그를 업데이트하는 메서드 ->:
updateDescription(desc: string, keywords: string, title: string) {
this.titleService.setTitle(title);
this.meta.updateTag({ name: 'description', content: desc })
this.meta.updateTag({ name: 'keywords', content: keywords })
this.meta.updateTag({ name: 'og:title', content: title })
this.meta.updateTag({ name: 'og:description', content: desc })
}
도움이 되길 바랍니다.
언급URL : https://stackoverflow.com/questions/48330535/dynamically-add-meta-description-based-on-route-in-angular
'programing' 카테고리의 다른 글
여러 열과 하나의 열을 연결할 때 공백이 null입니다(Oracle (0) | 2023.10.04 |
---|---|
WooCommerce 이메일 알림에서 로컬 픽업 시 발송 주소 숨기기 (0) | 2023.09.24 |
호출 함수에서 jquery ajax 콜백을 기다립니다. (0) | 2023.09.24 |
Mariadbin Centos 7을 사용한 INNER JOIN 사용자, 데이터베이스 및 데이터베이스 크기 (0) | 2023.09.24 |
iOS에서 다크 모드를 확인하는 방법은? (0) | 2023.09.24 |