Angular 5 - Stop errors from undefined object before loading data

后端 未结 4 1035
旧时难觅i
旧时难觅i 2021-02-15 13:57

What\'s the best way to prevent errors in console from objects that are still undefined?

Let\'s say I have this

name : string;
constructor(private data:          


        
相关标签:
4条回答
  • 2021-02-15 14:02

    You can use {{name?.value}} or {{name?}} inside component.html. Can make treatment to like this in compoment.ts ↓

       ````
    
        this.route.paramMap.pipe(
          map((param: ParamMap) => {
            // @ts-ignore
            return param.params.id;
          })
        ).subscribe(prodId => {
          this.id = prodId;
          this.productService.getSingleProduct(this.id).subscribe(prod => {
            this.product = prod;
            if (prod.images !== null) {
              this.thumbimages = prod.images.split(';');
            }`enter code here`
          });
        });
    
    
      ````
    
    0 讨论(0)
  • 2021-02-15 14:10

    As mentioned in previous responses you can use {{ name | async }} but remember if you want to use {{ name | async }}, name must be a promise or an observable.
    Otherwise you'll get an error like this :

    ERROR Error: InvalidPipeArgument: 'xxx' for pipe 'AsyncPipe'
    
    0 讨论(0)
  • 2021-02-15 14:14

    Just initialize your variable

    name : string = "";
    

    or you can do it inside of the constructor

    this.name = "";
    
    0 讨论(0)
  • 2021-02-15 14:25

    Multiple ways: You can use any one suitable to you.

    1. Adding ngIf : If name is undefined or null or '' it will not render the element and prevent errors in console. When name gets defined value it will automatically update the view.

    *ngIf="name"

    2. Adding async pipe : View will update whenever name gets defined. It waits for name to get defined.

    {{ name | async }}

    3. Adding fallback value : This is simply or condition. If name is undefined or null or '' , you can decide which fallback value to assign . {{ name || "" }}

    0 讨论(0)
提交回复
热议问题