无法以 Angular 4 提交表单

Posted

技术标签:

【中文标题】无法以 Angular 4 提交表单【英文标题】:cannot submit a form in angular 4 【发布时间】:2018-11-22 22:48:52 【问题描述】:

这是我的 login.component.html

    <form #user class="form-horizontal" method="post" (ngSubmit)="login($event)">
    <label for="email" class="cols-sm-2 control-label">Your Email</label>
    <div class="input-group">
        <span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
        <input type="text" class="form-control" name="email" [(ngModel)]="user.email"  placeholder="Enter your Email"/>
    </div>
    <label for="password" class="cols-sm-2 control-label">Password</label>
    <div class="input-group">
        <span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
        <input type="password" class="form-control" name="password"  [(ngModel)]="user.password" placeholder="Enter your Password"/>
    </div>
    <div class="form-group ">
        <button type="submit" class="btn btn-primary btn-lg btn-block login-button">Login</button>
    </div>
</form>

这是我的 login.component.ts 导出类 LoginComponent

user = email:'', password:'';
constructor (private dataservice: DataService)

//End of constructor

//Login Function
login()
    console.log(this.user);
    this.dataservice.loginValidate(this.user).subscribe(data => 
        console.log(data);
    ,error => 
        console.log(error);
    
);
//end of function

这是我的 data.service.ts

    @Injectable()
export class DataService 

    constructor(private http: HttpClient)

    //Method to login validate
    loginValidate(user) 
            const post_data =  this.http.post('http://localhost/charan/postdata.php',
            username: user.email,
            password: user.password
        ).subscribe(
            res => 
            console.log(res);
            
        );
    


当我尝试发布表单数据时,它显示以下错误:

错误类型错误:无法读取未定义的属性“订阅” 在 LoginComponent.push../src/app/login/login.component.ts.LoginComponent.login (login.component.ts:35) 在 Object.eval [as handleEvent] (LoginComponent.html:9) 在句柄事件(core.js:9953) 在 callWithDebugContext (core.js:11046) 在 Object.debugHandleEvent [as handleEvent] (core.js:10749) 在 dispatchEvent (core.js:7415) 在 core.js:8892 在 SafeSubscriber.schedulerFn [as _next] (core.js:3415) 在 SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:195) 在 SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:133)

这是我的 package.json


"名称": "exproj1", “版本”:“0.0.0”, “脚本”: “ng”:“ng”, “开始”:“ng服务”, “构建”:“ng构建”, “测试”:“ng测试”, “lint”:“ng lint”, “e2e”:“ng e2e” , “私人”:真的, “依赖”: "@angular/animations": "^6.0.3", "@angular/common": "^6.0.3", "@angular/compiler": "^6.0.3", "@angular/core": "^6.0.3", "@angular/forms": "^6.0.3", "@angular/http": "^6.0.3", "@angular/platform-b​​rowser": "^6.0.3", "@angular/platform-b​​rowser-dynamic": "^6.0.3", "@angular/路由器": "^6.0.3", "core-js": "^2.5.4", "rxjs": "^6.2.1", “zone.js”:“^0.8.26” , “开发依赖”: "@angular/compiler-cli": "^6.0.3", "@angular-devkit/build-angular": "~0.6.6", “打字稿”:“~2.7.2”, "@angular/cli": "~6.0.7", "@angular/language-service": "^6.0.3", "@types/jasmine": "~2.8.6", "@types/jasminewd2": "~2.0.3", "@types/node": "~8.9.4", "codelyzer": "~4.2.1", “茉莉花核”:“~2.99.1”, “茉莉花规格报告者”:“〜4.2.1”, "业力": "~1.7.1", "karma-chrome-launcher": "~2.2.0", “karma-coverage-istanbul-reporter”:“~2.0.0”, “业力茉莉花”:“〜1.1.1”, “karma-jasmine-html-reporter”:“^0.2.2”, "量角器": "~5.3.0", "ts-node": "~5.0.1", “tslint”:“~5.9.1”

请帮我解决这个问题。

提前致谢

【问题讨论】:

可以添加用于绑定表单值的'user'对象吗? 即使我遇到同样的错误 @RaedKhalaf 我不明白 你在表单[(ngModel)]="user.email"中使用了这个,这意味着login.component.ts中有一个'user'对象,你可以将它的实现添加到问题主体? @RaedKhalaf,感谢您的回复。我刚刚将用户定义为“用户”;在 login.component.ts 的构造方法之上。 【参考方案1】:
    name[(ngModel)] 的值应该相同。 您必须在 login.component.ts 文件中创建一个用户对象。

我可以展示一个代码示例。

login.component.html

<form class="pt-3" (submit)="onLogin()">
          <div class="form-group">
            <label>Email</label>
            <input type="text" class="form-control" [(ngModel)]="email" name="email" placeholder="Enter email">
            <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
          </div>
          <div class="form-group">
              <label>Password</label>
              <input type="password" [(ngModel)]="password" name="password" class="form-control" placeholder="should have min. 6 character with a number">
          </div>
          <div class="form-check">
            <input type="checkbox" class="form-check-input" id="exampleCheck1">
            <label class="form-check-label" for="exampleCheck1">Keep Me logged in for 7 days</label>
          </div>
          <button type="submit" class="btn btn-primary mt-3">Login</button>
        </form>

login.component.ts

export class LoginComponent implements OnInit 
   email: String;
   password : String;
    onLogin()
        const user = 
          email: this.email,
          password: this.password
        

        this.authService.authenticateUser(user).subscribe(data => 
          if(data.success)
            this.authService.storeUserData(data.token, data.user);
            this.flashMessage.show('succefully loggedin !', cssClass: 'alert-success', timeout: 5000);
            this.router.navigate(['/user/dashboard']);
           else 
            this.flashMessage.show(data.msg, cssClass: 'alert-danger', timeout:2000);
            this.router.navigate(['/auth/login']);
          
        );
      

auth.service.ts

authenticateUser(user)
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post(this.url + `/users/authenticate`, user, headers: headers)
      .map(res => res.json())
  

希望这对您有所帮助。

【讨论】:

显示错误 this.http.post(...) map is not a function 添加导入'rxjs/add/operator/map';在您的 auth.service.ts 文件中。 我这样做了,它显示错误 - 错误 TS2339 property subscribe does not exist on type void 我认为您使用的是 Angular 6。我在使用 Angular 6 时遇到了此类问题。您能给我看看 package.json 文件吗? 我已经在上面添加了package.json。【参考方案2】:

从表单中删除#user ref 或更改其名称。如果你在 ts 中使用这个实例,那就有问题了。

【讨论】:

你已经定义了用户;你应该定义像 user = email : "", password : "" 这样的用户对象 我已经按照你说的定义了,现在我收到了错误,因为响应没有定义 这是您的服务代码//let user = Response.json(); 中的注释行,那么您在哪里收到此错误,请告诉我。如果您取消注释此行,那么这是错误的,它应该是 let user = response.json() 这行显示错误 ").map(response: Response) => "

以上是关于无法以 Angular 4 提交表单的主要内容,如果未能解决你的问题,请参考以下文章

Angular - 以编程方式提交表单

无法在 Angular 2 应用程序中提交 HTML 表单

防止使用 angular.js 提交多个表单 - 禁用表单按钮

Angular 4 表单重置提交到服务器

在 Angular 单元测试中使用回车键提交表单

在Angular 4中提交表单后清除输入框