Канонический URL в угловой - PullRequest
0 голосов
/ 01 октября 2019

Я попытаюсь объяснить мою проблему, я определил сервис для настройки заголовка страницы, мета-описания и канонического URL, но мой веб-сайт имеет перенаправление, потому что сначала он загружает основной компонент, а Google обнаруживает данные этого компонента.

Как мне избежать этого перенаправления или загрузки основного компонента?

Это мой "Seo Service.ts"

import {Injectable, Inject, Optional, RendererFactory2, ViewEncapsulation } from '@angular/core'; 
import { Meta, Title } from '@angular/platform-browser';
import { DOCUMENT } from '@angular/common';

@Injectable({
    providedIn: 'root'
})
export class SEOService {
  constructor(private title: Title, private meta: Meta, @Inject(DOCUMENT) private dom, private rendererFactory: RendererFactory2) { }


  updateTitle(title: string) {
    this.title.setTitle(title);
  }

  updateOgUrl(url: string) {
    this.meta.updateTag({ name: 'og:url', content: url })
  }

  updateOgTitle(title: string) {
    this.meta.updateTag({ name: 'og:title', content: title })
  }

  updateOgdescription(description: string) {
    this.meta.updateTag({ name: 'og:description', content: description })
  }

  updateOgType(type: string) {
    this.meta.updateTag({ name: 'og:type', content: type })
  }

  updateOgImage(urlImage: string) {
    this.meta.updateTag({ name: 'og:image', content: urlImage })
  }

  setNoindex() {
    this.meta.updateTag({ name: 'robots', content: 'NoIndex, Follow' })
  }

  setIndex() {
    this.meta.updateTag({ name: 'robots', content: 'Index, Follow' })

  }

  updateDescription(desc: string) {
    this.meta.updateTag({ name: 'description', content: desc })
  }

  updateKeywords(keywords: string) {
    this.meta.updateTag({ name: 'keywords', content: keywords })
  }

  createCanonicalURL() {
      let link: HTMLLinkElement = this.dom.createElement('link');
      link.setAttribute('rel', 'canonical');
      this.dom.head.appendChild(link);
      link.setAttribute('href', this.dom.URL);
   }
   /**
   * Inject the State into the bottom of the <head>
   */
  addTagCanonical(tag: LinkDefinition, forceCreation?: boolean) {

      try {
          const renderer = this.rendererFactory.createRenderer(this.dom, {
              id: '-1',
              encapsulation: ViewEncapsulation.None,
              styles: [],
              data: {}
          });

          const link = renderer.createElement('link');
          const head = this.dom.head;
          const selector = this._parseSelector(tag);

          const children = head.children;
          for (var idx = 0; idx < children.length; idx++) {
              if (children[idx].localName === 'link' && children[idx].rel === tag.rel)
                  renderer.removeChild(head, children[idx]);
          }

          if (head === null) {
              throw new Error('<head> not found within DOCUMENT.');
          }

          Object.keys(tag).forEach((prop: string) => {
              return renderer.setAttribute(link, prop, tag[prop]);
          });

          // [TODO]: get them to update the existing one (if it exists) ?
          renderer.appendChild(head, link);

      } catch (e) {
          console.error('Error within linkService : ', e);
      }
  }

  private _parseSelector(tag: LinkDefinition): string {
      // Possibly re-work this
      const attr: string = tag.rel ? 'rel' : 'hreflang';
      return `${attr}="${tag[attr]}"`;
  }
}

 export declare type LinkDefinition = {
  charset?: string;
  crossorigin?: string;
  href?: string;
  hreflang?: string;
  media?: string;
  rel?: string;
  rev?: string;
  sizes?: string;
  target?: string;
  type?: string;
} & {
    [prop: string]: string;
};

Это мой "основной маршрутизации.module.ts "

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CoreComponent } from './core.component';

const routes: Routes = [
  { path: 'master', loadChildren: '../admin/admin.module#AdminModule' },
  {
    path: '', component: CoreComponent,
    children: [
       {
        path: 'search/:city/:genre/:page',
        loadChildren: './talent/talent.module#TalentModule',
        data: {
          title: 'Some title',
          description : 'some description' 
        }
      },
      {
        path: 'search',
        loadChildren: './talent/talent.module#TalentModule',
        data: {
          title: 'Some title',
          description : 'some description' 
        }
      },
      {
        path: 'search/:city',
        loadChildren: './talent/talent.module#TalentModule',
        data: {
          title: 'Some title',
          description : 'some description' 
        }
      },
      {
        path: 'search/:city/:genre',
        loadChildren: './talent/talent.module#TalentModule',
        data: {
          title: 'Some title',
          description : 'some description' 
        }
      },
      { path: 'contact', loadChildren: './contact/contact.module#ContactModule' },
      { path: 'aboutus', loadChildren: './nosotros/nosotros.module#NosotrosModule' },
      { path: 'profile', loadChildren: './profile/profile.module#ProfileModule' },
      { path: 'getmyaccount', loadChildren: './getmyaccount/getmyaccount.module#GetmyaccountModule' },
      { path: 'notfound', loadChildren: './notfound/notfound.module#NotfoundModule', data: {
          title: 'Some titletrada',
          description : 'Some description' 
        } },
      { path: '', component: CoreComponent },
      { path: 'home', loadChildren: './home/home.module#HomeModule' },
      { path: '**', redirectTo: 'notfound' },
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CoreRoutingModule { }

А это мой" app-routing.module.ts "

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path: '', loadChildren: './core/core.module#CoreModule'},
  { path: 'master', loadChildren: './admin/admin.module#AdminModule' },
  { path: 'login', loadChildren: './login/login.module#LoginModule' },
  { path: 'signup', loadChildren: './signup/signup.module#SignupModule' },
  { path: 'verify/:key', loadChildren: './verify/verify.module#VerifyModule' },
  { path: '**', redirectTo: '' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { initialNavigation: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }
...