用Javascript解构对象-ngbind-Angular 4+

时间:2018-10-15 07:33:51

标签: javascript arrays angular object

有人可以告诉我如何在Ang-bind 4+中使用变形数据吗?

我已经遇到了如何使用here中的变形对象/数组。

const wes = {
  first: 'Wes',
  last: 'Bos',
  links: {
    social: {
      twitter: 'https://twitter.com/wesbos',
      facebook: 'https://facebook.com/wesbos.developer',
    },
    web: {
      blog: 'https://wesbos.com'
    }
  }
};

尝试如下绑定数据:

let {first : f, last:l}  =wes;

在html中,我只使用了{{f}}

但是它什么也没显示。我听错了吗?

请参考我所做的事情:stackblitz

谢谢

2 个答案:

答案 0 :(得分:2)

您不能直接使用成角度的对象分解,因为它需要直接绑定到组件。

获取示例,您可以执行以下操作:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular 4';
  count = 5;

  _destructuring = '';  
  ngOnInit() {
    const tmp = {a: 'hello'};
    const {a: _destructuring} = tmp;
    this._destructuring = _destructuring;
  }
}

更新的示例: https://stackblitz.com/edit/angular-ngmodel-write-value-er4dcv?file=app/app.component.ts

或者,您可能想在角度组件的Object.assign上使用this。但是,这将涉及编写远远超出需要的代码,所以...

编辑:根据要求,以下是带有原始对象的示例代码,以及(有效的)示例:https://stackblitz.com/edit/angular-ngmodel-write-value-lf97lr?file=app/app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular 4';
  count = 5;

  _destructuring = '';
  _nested = {};

  ngOnInit() {
    const tmp = {a: 'hello'};
    const {a: _destructuring} = tmp
    this._destructuring = _destructuring;

    // Original (nested) object
    const wes = {
      first: 'Wes',
      last: 'Bos',
      links: {
        social: {
          twitter: 'https://twitter.com/wesbos',
          facebook: 'https://facebook.com/wesbos.developer',
        },
        web: {
          blog: 'https://wesbos.com'
        }
      }
    };
    // Object destructuring (links.social.facebook -> fb, links.social.twitter -> tw)
    const {
      links: {
        social: {
          facebook: fb,
          twitter: tw
        }
      }
    } = wes;

    // Assign to the local property, available in the component.
    Object.assign(this._nested, {
      fb: fb,
      tw: tw
    });
  }
}

答案 1 :(得分:0)

效果似乎很好:

const person = {
  first: 'John',
  last: 'Doe',
};

const { first, last } = person;
const { first: f, last: l } = person;

console.log(first, last);
console.log(f, l);