2017-07-22 262 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

相关问题