Angular 4无法读取属性'替换'未定义的错误

时间:2017-07-22 18:30:16

标签: javascript angular typescript

我在Angular 4中使用.replace() JS函数在其中一个字符串上删除几个字符。在组件中,我编写了如下代码:

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

 constructor() {}

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

1 个答案:

答案 0 :(得分:0)

如果您订阅某个URL,请将替换放在订阅中,如下所示

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

      }
})