Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 当从LocalStorage为对象赋值时,如何在typescript对象中创建实例方法_Angular_Typescript - Fatal编程技术网

Angular 当从LocalStorage为对象赋值时,如何在typescript对象中创建实例方法

Angular 当从LocalStorage为对象赋值时,如何在typescript对象中创建实例方法,angular,typescript,Angular,Typescript,我是Java开发人员,但我正在尝试使用typescript 这是我的用户对象: export class User { id: string; name: string; email?: string; unit: string; street: string; postalcode: string; paymentmode: string; public isComplete(): boolean { i

我是Java开发人员,但我正在尝试使用typescript

这是我的用户对象:

export class User
{
    id: string;
    name: string;
    email?: string;
    unit: string;
    street: string;
    postalcode: string;
    paymentmode: string;

    public isComplete(): boolean
    {
        if(this.id != null && this.email != null && this.isAddress()){ return true}
        else return false;
    }

    public isAddress(): boolean
    {
        if(this.street != null && this.postalcode != null){ return true}
        else return false
    }


}
还有另外一个打字稿

var user = new User();
user = this.loginService.getLocalUser();
我假设localStorage被解析为user

我无法以这种方式访问isComplete方法

user.isComplete()
相反,我需要将其用作静态对象

User.isComplete
我的getLocaluser:

getLocalUser(): User {
        var user = new User();
        user = JSON.parse(localStorage.getItem('user'));

        return user;
    }
我怎样才能做到呢


您只需要这样做:

var user = new User;

user.isComplete();
编辑问题后,如果我理解正确,您需要使用名称空间三重斜杠指令,如下所示: 在第一个文件中,a.ts例如:

namespace myNameSpace{
    export class User
    {
        id: string;
        name: string;
        email?: string;
        unit: string;
        street: string;
        postalcode: string;
        paymentmode: string;

        public isComplete(): boolean
        {
            if(this.id != null && this.email != null && this.isAddress()){ return true}
            else return false;
        }

        public isAddress(): boolean
        {
            if(this.street != null && this.postalcode != null){ return true}
            else return false
        }
    }
}
/// <reference path="a.ts" />
namespace myNameSpace{
    var user = new User();
    //user = this.loginService.getLocalUser(); //this function need to be checked in your environment
    user.isComplete();
}
在第二个文件中b.ts例如:

namespace myNameSpace{
    export class User
    {
        id: string;
        name: string;
        email?: string;
        unit: string;
        street: string;
        postalcode: string;
        paymentmode: string;

        public isComplete(): boolean
        {
            if(this.id != null && this.email != null && this.isAddress()){ return true}
            else return false;
        }

        public isAddress(): boolean
        {
            if(this.street != null && this.postalcode != null){ return true}
            else return false
        }
    }
}
/// <reference path="a.ts" />
namespace myNameSpace{
    var user = new User();
    //user = this.loginService.getLocalUser(); //this function need to be checked in your environment
    user.isComplete();
}
//
名称空间myNameSpace{
var user=新用户();
//user=this.loginService.getLocalUser();//需要在您的环境中检查此函数
user.isComplete();
}
使用此

let user = new User().deserialize(this.loginService.getLocalUser());
现在,在
用户
模型中添加一个
反序列化()
方法

deserialize(input: any): User {
    let self: any = this;
    for (let prop in input) {
            self[prop] = input[prop];
    }
    return self;
}

当您使用
parse()
调用web服务并将其映射到
User
对象时,不会创建它的实例方法,因为它们不驻留在
响应中只需创建一个新的
User
对象副本,并从响应中逐个复制值。

只需使用从
localStorage
检索的解析JSON数据实例化
User
类即可

getLocalUser
方法更改如下:

getLocalUser(): User {
    let userData = JSON.parse(localStorage.getItem('user'));
    let user = new User(userData);

    return user;
}
现在,当您有新实例时,通常可以使用该类的已定义实例方法:

let user = this.loginService.getLocalUser();
let isComplete = user.isComplete();

console.log(isComplete); // => true/false
此外,您还没有将构造函数放入
User
类:

export class User
{
    id: string;
    name: string;
    // ...

    constructor(userData: any) {
        this.id = userData.id;
        this.name = userData.name;
        // ...
    }

    public isComplete(): boolean
    {
        if(this.id != null && this.email != null && this.isAddress()){ return true}
        else return false;
    }

    // the rest of the methods...

}

错误源于这里的JSON.parse(localStorage.getItem('user')

此语句返回的对象不是
User
类型的对象,因此没有
isComplete
成员方法

@响尾蛇的解决方案对你来说应该足够了。但是代码就这样变得动态了

然而,我更喜欢完全类型化的解决方案,因为这是使用TS的一个重要目标

export interface User
{
    id: string;
    name?: string;
    ...
}

function isComplete(user: User) { 
    if (user.id != null && user.email != null ) { 
        return true;
    }
    return false;
}

function getLocalUser(): User {
    var user = JSON.parse(localStorage.getItem('user')) as User;
    return user;
}

var user = getLocalUser();
console.log(isComplete(user)); // true or false
对模型使用接口而不是类可能会很奇怪。它适用于我使用过的最流行的框架,这些框架是用TS编写的,例如Angular、RxJs。这同样适用于DefinitelyTyped的定义。当然,在某些情况下,上课是更好的解决办法。我会给你留个空间让你知道

通过创建一个通用包装器,您甚至可以进一步严格地键入
localStorage

export class LocalStorageService {
    private storage = localStorage;

    get<T>(key: string): T {
        var serialized: string = this.storage.getItem(key);
        return serialized ? <T>JSON.parse(serialized) : undefined;
    }

    set<T>(key: string, data: T) {
        var serialized: string = JSON.stringify(data);
        this.storage.setItem(key, serialized);
    }

    remove(key: string) {
        this.storage.removeItem(key);
    }
}
导出类LocalStorageService{
私有存储=本地存储;
get(key:string):T{
var序列化:string=this.storage.getItem(键);
return serialized?JSON.parse(serialized):未定义;
}
集合(键:字符串,数据:T){
var序列化:string=JSON.stringify(数据);
this.storage.setItem(键,序列化);
}
删除(键:字符串){
此.storage.removietem(键);
}
}
试试这个

var user=(this.loginService.getLocalUser());
简单地说:

getLocalUser(): User {
    return Object.assign(new User(), JSON.parse(localStorage.getItem('user')));
}
你在哪里(之后):

将所有可枚举自身属性的值从一个或多个源对象复制到目标对象

它将返回目标对象


因此,您最终得到了新创建的
用户实例,以及解析JSON中的所有道具。

您想使您的方法成为静态的吗?这些是实例方法您正在创建新实例吗?像
var user=new user()
?从您的示例来看,似乎缺少此部分。
user=this.loginService.getLocalUser()
可以返回一个完全不同的对象。它说isComplete()不是函数什么时候?在编译过程中?不,当我运行程序时!我认为OP最关心的是这个问题。他应该问一下本地存储,我更新了我的答案。希望我理解正确。