2017-07-22 52 views
-1

我正在使用.replace() Angular 4中的JS函數在其中一個字符串上剝去幾個字符。在組件中,我寫了下面的代碼:Angular 4無法讀取屬性'取代'未定義的錯誤

@Component({...}) 
export class SomeComponent implements OnInit { 
routerUrl: string = ''; 

constructor() {} 

ngOnInit() { 
    this.routerUrl = "SOME_DYNAMICALLY_RETRIEVED_STRING"; 
    this.routerUrl = this.routeUrl.replace(/[`[email protected]#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, ''); 
    console.log(this.routerUrl); 
} 

但代碼拋出一個錯誤

ERROR TypeError: Cannot read property 'replace' of undefined 
at SafeSubscriber._next ... 

請幫我解決這個問題。

添加的代碼

export class CourseComponent implements OnInit { 
routeUrl: string = ''; 

    constructor(private renderer: Renderer2, private route: ActivatedRoute) {} 

    ngOnInit() { 
    this.route.params.subscribe((params: Params) => { 
     this.routeUrl = params[':name']; 
     this.routeUrl = this.routeUrl.replace(/[`[email protected]#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, ''); 
     console.log(this.routeUrl); 
    }) 
    } 
} 
+0

'replace'不會在原地工作(它不」 t mutate)。你必須分配它。 'this.routeUrl = this.routeUrl.replace(...)' –

+0

我懷疑錯誤來自代碼中的其他地方,因爲錯誤消息的SafeSubscriber._next部分。或者,在執行代碼時,不會設置SOME_DYNAMICALLY_RETRIEVED_STRING。順便說一句,那個正則表達式應該做什麼? –

+0

@Kinduser是的,但是這並不能解釋他得到的錯誤。 –

回答

0

如果你訂閱一些URL,將內部認購替換如下

this.router.url.subscribe((routeparams){ 
    this.routerUrl = "SOME_DYNAMICALLY_RETRIEVED_STRING"; 
    if(this.routerUrl){ 
     this.routerUrl = 
     this.routeUrl.replace(/[`[email protected]#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, ''); 

     } 
}) 
+0

也可以通過訂閱發佈整個代碼 – Aravind

相關問題