angular
  • angular2-routing
  • 2016-05-31 66 views 0 likes 
    0

    目前我硬編碼鏈路,諸如以下共享角2當前路線要在鏈接在,微博和Facebook

    <a href="https://twitter.com/home?status=http%3A//www.beeps.com%3A7002/index.html" class="SHARE TWITTER" onclick='window.open(this.href,"popupwindow", "width=800,height=500,left=200,top=5,scrollbars,toolbar=0,resizable"); return false;' target="social"></a> 
    

    Facebook的:

    <a href="https://www.facebook.com/sharer/sharer.php?u=http%3A//www.beeps.com%3A7002/index.html" class="SHARE FACEBOOK" onclick='window.open(this.href,"popupwindow", "width=800,height=500,left=200,top=5,scrollbars,toolbar=0,resizable"); return false;' target="social"></a> 
    

    從Linked In,Twitter或Facebook引用時,所有這些鏈接似乎都有效 - 但我想創建一個Angular 2,它基於當前的Angular 2路線替換<a>元素的&url=http%3A//www.beeps.com%3A7002/index.html部分,所以我們沒有對每個頁面進行硬編碼。

    回答

    1

    我最終採取的方法是創建一個route.watcher.service.ts,填充包含當前路由URL的變量 - 對於我需要創建的每個社交媒體共享,我只需使用組件函數從route.watcher.service.ts複製路由URL值是綁定到特定社交媒體共享組件內的錨定屬性的數據。

    路線觀察家服務:

    import {Injectable} from "@angular/core"; 
    import {Router} from '@angular/router'; 
    
    @Injectable() 
    export class RouteWatcherService { 
        private routeUrl:string; 
    
        constructor(private router:Router) { 
         this.router.changes.subscribe(() => { 
          this.routeUrl = this.router.serializeUrl(this.router.urlTree); 
         }); 
        } 
    
        url():string { 
         return this.routeUrl; 
        } 
    } 
    

    Twitter分享組件:

    import {Component} from '@angular/core'; 
    import {RouteWatcherService} from '../route.watcher.service'; 
    
    @Component({ 
        moduleId: module.id, 
        selector: 'twitter-component', 
        templateUrl: 'twitter.component.html' 
    }) 
    
    export class TwitterComponent { 
        constructor(private routeWatcher:RouteWatcherService) {} 
    
        routeHref() { 
         return window.location.protocol + '//' + window.location.host + this.routeWatcher.url(); 
        } 
    } 
    

    Twitter分享組件HTML模板:

    <a href="https://twitter.com/home?status={{routeHref()}}" class="SHARE TWITTER" onclick='window.open(this.href,"popupwindow", "width=800,height=500,left=200,top=5,scrollbars,toolbar=0,resizable"); return false;' target="social"></a> 
    
    相關問題