【Angular 2+】 监听路由动态设置页面meta

angular2+ 里默认切换路由或者切换组件,页面的meta是不会变化的。
如果想针对每个路由设置页面标题,要使用 Meta 服务,我们需要从 @angular/platform-browser 库导入 Meta 类,然后利用 Angular 依赖注入的机制,通过构造注入的方式注入 Meta 服务。其Meta Service 提供了addTag()、addTags()、getTag()、getTags()、updateTag()、removeTag()、removeTagElement()方法。

1. route设置页面
import { Routes } from '@angular/router';

import { HeroesComponent } from './heroes/heroes.component';
import { HomeComponent } from './home/home.component'

export const rootRouterConfig: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent, data: { title: 'Home-Liu', description: 'home页面', keywords: 'Angular, RxJS, TypeScript, home' } },
  { path: 'heroes', component: HeroesComponent, data: { title: 'heros-Liu', description: 'heroes页面', keywords: 'Angular, RxJS, TypeScript, heroes' } }
]

2. app.component.ts页面
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

import { Component } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Meta } from '@angular/platform-browser';

export class AppComponent {
  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private meta: Meta
  ) { }
  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.meta.updateTag({ name: 'description', content: event['description'] });
        this.meta.updateTag({ name: 'keywords', content: event['keywords'] })
      });
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例: 1. 安装依赖 ``` npm install --save @angular/material @angular/cdk @angular/flex-layout ``` 2. 导入模块和组件 在 `app.module.ts` 中导入以下模块和组件: ```typescript import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { FlexLayoutModule } from '@angular/flex-layout'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, HttpClientModule, MatInputModule, MatButtonModule, MatIconModule, MatCardModule, FlexLayoutModule ], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} ``` 3. 编写组件模板和样式 在 `app.component.html` 中编写组件模板: ```html <div fxLayout="column" fxLayoutAlign="center center"> <mat-card> <mat-card-header> <mat-card-title>上传文件</mat-card-title> </mat-card-header> <mat-card-content> <input type="file" (change)="onFileSelected($event)" /> <mat-card *ngIf="previewUrl"> <mat-card-header> <mat-card-title>预览</mat-card-title> </mat-card-header> <img [src]="previewUrl" /> </mat-card> </mat-card-content> <mat-card-actions> <button mat-raised-button color="primary" (click)="uploadFile()">上传</button> </mat-card-actions> </mat-card> </div> ``` 在 `app.component.css` 中编写组件样式: ```css mat-card { margin-top: 20px; max-width: 500px; } img { max-width: 100%; max-height: 300px; } ``` 4. 编写组件代码 在 `app.component.ts` 中编写组件代码: ```typescript import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { file: File | null = null; previewUrl: string | null = null; constructor(private httpClient: HttpClient) {} onFileSelected(event: any) { this.file = event.target.files[0]; this.preview(); } preview() { if (!this.file) { this.previewUrl = null; return; } const reader = new FileReader(); reader.readAsDataURL(this.file); reader.onload = () => { this.previewUrl = reader.result as string; }; } uploadFile() { if (!this.file) { return; } const formData = new FormData(); formData.append('file', this.file); this.httpClient.post('http://example.com/upload', formData).subscribe( response => { console.log(response); }, error => { console.error(error); } ); } } ``` 这个组件包括三个方法: - `onFileSelected`:当用户选择文件时触发,将文件存储到 `file` 变量中,并调用 `preview` 方法预览文件。 - `preview`:使用 `FileReader` 对象读取 `file` 变量中的文件,并将预览结果存储到 `previewUrl` 变量中。 - `uploadFile`:将 `file` 变量中的文件上传到服务器。 需要注意的是,这个示例代码中上传的 URL 地址是假的,需要根据实际情况修改。同时,也需要在后端代码中对文件上传进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值