无法读取未定义的 属性 'variable' (Typescript / HTML / Nativescript)

Cannot read property 'variable' of undefined (Typescript / HTML / Nativescript)

我正在编写 Nativescript-Angular2-Typescript 应用程序,但目前 运行 总是出现 TypeError。

现在的以下代码已针对调试目的进行了调整。

login.component.html

    <StackLayout>
    <Image src="res://icon" stretch="none" horizontalAlignment="center"></Image>
    <TextField [(ngModel)]="user.phonenr" hint="mobile phone number" keyboardType="phone" autocorrect="false"></TextField>
    <TextField hint="SMS code" secure="true"></TextField>
    <Button text="login" class="submit-button" (tap)="submitnr()"></Button>
    <Button text="register" class="btn"></Button>
    </StackLayout>

login.component.ts

    import { Component } from "@angular/core";
    import { Button } from "tns-core-modules/ui/button";
    import { User } from '../../shared/user/user';
    import { UserService } from "../../shared/user/user.service";


    @Component({
    selector: "Login",
    providers: [UserService],
    moduleId: module.id,
    templateUrl: "./login.component.html",
    styleUrls: ['./login-common.css']
    })

    export class LoginComponent {

    //Variables
    public user: User;       

    constructor(private userService: UserService) {
    this.user = new User();
    this.user.phonenr = 2222555;
    }

    public submitnr() {
    if (this.user.phonenr === undefined)
    {
    console.log("fucking undefined why ??????");
    console.log(this.user.phonenr);
    }
    else
    {
    console.log("Its defined so why getting error!!!!!!????!??!!?");
    console.log(this.user.phonenr);
    }
    }
    }

user.ts:

    export class User {
    phonenr: number | undefined;
    }

user.service.ts:

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { User } from './user';


    @Injectable()
    export class UserService {

    constructor(private http: HttpClient) { }

    public register(user: User) {
    console.log(user.phonenr);
    }
    }

"login.component.html" 中的 "user.phonenr" 部分总是抛出错误: 类型错误:无法读取未定义的 属性 'phonenr'

只是提到 submitnr() 运行s 的 If 指令到定义的部分。

我希望我提供了所有必要的代码。如果不告诉我。

你的代码看起来是正确的,我只能建议你在输入中添加 *ngIf="user",即使它不能直接解决问题,它也可能会有所帮助

并且...如果您将 class 替换为界面?