简体   繁体   中英

Angular HttpParams to object, Object.defineProperty creates property but is out of scope

I am trying to transform HttpParams into an object by dynamically creating the properties on the object based off what is in HttpParams.

private transformParamsToObject(params: HttpParams) {
    let newObject = {};
    params.keys().forEach(x => Object.defineProperty(newObject, x, { value: params.get(x) }));
    const foo = Object.assign({}, newObject);
    return foo;
}

From what I can see in the debugger, it's defining the properties, but they don't seem to be in scope when I assign that object to foo. Even if I just return newObject, it doesnt have the properties defined on them in scope.

I feel like I may be missing something very simple here. Can anyone help?

They are not enumerable , that's why Object.assign doesn't find them. But there's no reason to use Object.defineProperty here when you can just assign the property directly, and there's no reason to use Object.assign to create yet another foo object next to newObject . Just do

private transformParamsToObject(params: HttpParams) {
    let newObject = {};
    for (const x of params.keys())
        newObject[x] = params.get(x);
    return newObject;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM