Angular-2 : Change favicon icon as per configuration

可紊 提交于 2019-12-02 21:59:05
Parshwa Shah

You can use jQuery/JS in your service. Make a function that will load your app favicon dynamically like this:

app.module.ts

import {NgModule} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './path/to/app.component';
import {AppService} from './path/to/app.service';
// ....

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        // ...
    ],
    bootstrap: [AppComponent],
    providers: [AppService]
})
export class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

app.service.ts

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';


@Injectable()
export class AppService {

    constructor(private http: Http) {}

    getAppDetails(appId: string) {

            return this.http.post(url, appId)
                .map((response: Response) => {
                    let details = response.json();
                    return details;
                })
                .do(data => console.log(data))
                .catch(this.handleError);
    }

     private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }

    setAppFavicon(id: string, basepath: string, icon: string)
    {
        $("#"+id).attr("href", basepath+"/"+ icon);
    }
}

app.component.ts:

import {Component} from "@angular/core";
import {AppService} from "../path/to/app.service";


@Component({
    selector: 'application',
    templateUrl: './path/to/app.component.html'
})
export class ApplicationComponent {

    details: any;

    constructor(private appService: AppService) {

        this.details = appService.getAppDetails(id);
        appService.setAppFavicon(id,basepath,this.details.icon);

    }


}

In index.html set link tag

<link id="appFavicon" rel="icon" type="image/x-icon" href="favicon.ico">

and somewhere in your code import

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

constructor(@Inject(DOCUMENT) private _document: HTMLDocument) {}

and use it like this

this._document.getElementById('appFavicon').setAttribute('href', '/your/icon/path.ico');

Angular 5.0 >

import { DOCUMENT } from '@angular/platform-browser';
shershen

Then you can use javascript to set favicon per configuration by adding following function to your <script> block:

 <script>

        document.SYSTEMJS_CONFIG.map.app = 'scripts/configs';

        document.SYSTEMJS_CONFIG.packages.app = { main: 'application.ts', defaultExtension: 'ts' };

        System.config(document.SYSTEMJS_CONFIG);

        System.import('app').catch(function (err) {
            console.error(err);
        });        

//here favicon is set
(function() {
    var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = '../path/to/xyz.png'; //path to selected favicon file
    document.getElementsByTagName('head')[0].appendChild(link);
}());

    </script>

We have nodejs running in the back-end, we have URL specific favicon to display as a requirement.

In app.js we implemented a resolveConfig() function which will help us to get the url specific configuration.

The return value of above function is used in get favicon call as below.

app.js

app.get('/favicon.ico',(req,res)=> {
   let key = resolveConfig(req.hostname);
   switch (key) {
     case 'a':
       res.sendFile(__dirname + '/dist/assets/a.ico');
       break;
     case 'b':
       res.sendFile(__dirname + '/dist/assets/b.ico');
       break;
   }
});

index.html

<link rel="icon" type="image/x-icon" href="favicon.ico"/>

*this might be useful if you have a nodejs in backend.

Outside <application></application>, you can to use only Title class:

import {Title} from '@angular/platform-browser';

export class YourClass(){

  constructor(private title: Title){}

  yourNameMethod(){
    this.title.setTitle('your title');
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!