小编Fra*_*ica的帖子

TS中字符串枚举和字符串文字类型之间的差异

假设我想确保myKey{ myKey: '' }只包含字符串foo,bar,baz,我可以通过两种方式实现这一目标.

   // with a String Literal Type 
   type MyKeyType = 'foo' | 'bar' | 'baz';

    // or with a String Enum   
    enum MyKeyType {
       FOO = 'foo',
       BAR = 'bar',
       BAZ = 'baz'
    }
Run Code Online (Sandbox Code Playgroud)

我想知道其中一个的利弊在哪里,因为两个看起来都是一样的(从我访问例如条件检查的值的方式来看).

我在TS文档中发现的唯一区别是Enums是运行时的真实对象,在某些情况下可能是可取的.

typescript

42
推荐指数
5
解决办法
3897
查看次数

将Angular组件从许多输入/输出重构为单个配置对象

我的部件通常由具有多开始了@Input@Output性能.当我添加属性时,将单个配置对象切换为输入似乎更简洁.

例如,这是一个具有多个输入和输出的组件:

export class UsingEventEmitter implements OnInit {
    @Input() prop1: number;
    @Output() prop1Change = new EventEmitter<number>();
    @Input() prop2: number;
    @Output() prop2Change = new EventEmitter<number>();

    ngOnInit() {
        // Simulate something that changes prop1
        setTimeout(() => this.prop1Change.emit(this.prop1 + 1));
    }
}
Run Code Online (Sandbox Code Playgroud)

它的用法:

export class AppComponent {
    prop1 = 1;

    onProp1Changed = () => {
        // prop1 has already been reassigned by using the [(prop1)]='prop1' syntax
    }

    prop2 = 2;

    onProp2Changed = () => {
        // prop2 has already …
Run Code Online (Sandbox Code Playgroud)

javascript angular-components angular

19
推荐指数
3
解决办法
1228
查看次数

防止 ngOnChanges 在发出事件后触发(Angular 2+)

在 Angular 2+ 中,可以通过使用@Input@Output参数来实现自定义双向数据绑定。所以如果我想让子组件与第三方插件通信,我可以这样做:

export class TestComponent implements OnInit, OnChanges {
    @Input() value: number;
    @Output() valueChange = new EventEmitter<number>();

    ngOnInit() {
        // Create an event handler which updates the parent component with the new value
        // from the third party plugin.

        thirdPartyPlugin.onSomeEvent(newValue => {
            this.valueChange.emit(newValue);
        });
    }

    ngOnChanges() {
        // Update the third party plugin with the new value from the parent component

        thirdPartyPlugin.setValue(this.value);
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<test-component [(value)]="value"></test-component>
Run Code Online (Sandbox Code Playgroud)

在第三方插件触发事件通知我们发生变化后,子组件通过调用this.valueChange.emit(newValue). 问题是,ngOnChanges然后在子组件中触发,因为父组件的值已更改,从而导致thirdPartyPlugin.setValue(this.value) …

javascript typescript angular

5
推荐指数
2
解决办法
6886
查看次数

找出对象是否具有相同的键

我有一对物体.我试图找出它们是否都有相同的键,如下所示:

let a = { user1: true, user2: true }
let b = { user1: true, user3: true }
hasSameKeys(a, b) => false

let a = { user1: true, user2: true }
let b = { user2: true, user1: true }
hasSameKeys(a, b) => true
Run Code Online (Sandbox Code Playgroud)

我也在使用_underscore.js

提前致谢

约翰S.

javascript algorithm underscore.js

0
推荐指数
1
解决办法
142
查看次数