【问题标题】:How to implement Angular reactive form using service?如何使用服务实现 Angular 反应式表单?
【发布时间】:2019-05-24 03:03:24
【问题描述】:

我正在尝试使用 Angular 反应式表单来实现登录表单。我不知道如何将表单值传递给服务中的登录功能以发出发布请求。我主要在服务组件中的登录功能上苦苦挣扎...................................... ..................................................... ..................................................... ..................................................... ...................................

代码如下:

component.html

    <div class="page-wrap height-100 mat-bg-primary">
    <div class="session-form-hold">
    <mat-progress-bar mode="determinate" class="session-progress"></mat- 
     progress-bar>
     <mat-card>
      <mat-card-content>
        <div class="text-center pb-1">

          <p class="text-muted m-0">Sign in to your account</p>
        </div>
        <form [formGroup]="signinForm" (ngSubmit)="signin()">
          <div class="">
            <mat-form-field class="full-width">
              <input
                type="username"
                name="username"
                matInput
                [(ngModel)]="username" 
                placeholder="username"
                value="">
            </mat-form-field>
            <small 
              *ngIf="signinForm.controls['username'].hasError('required') && 
       signinForm.controls['username'].touched" 
              class="form-error-msg"> Username is required </small>
          </div>

          <div class="">
            <mat-form-field class="full-width">
              <input 
                type="password"
                name="password"
                matInput
                [formControl]="signinForm.controls['password']"
                placeholder="Password" 
                value="">
            </mat-form-field>
            <small 
              *ngIf="signinForm.controls['password'].hasError('required') && 
       signinForm.controls['password'].touched" 
              class="form-error-msg"> Password is required </small>
          </div>
          <button mat-raised-button class="mat-primary full-width mb-1" 
         [disabled]="signinForm.invalid">Sign in</button> 
        </form>
      </mat-card-content>
    </mat-card>
  </div>
</div>

component.ts

     import { Component, OnInit, ViewChild } from '@angular/core';
     import { MatProgressBar, MatButton } from '@angular/material';
     import { Validators, FormGroup, FormControl } from '@angular/forms';
     import { Router } from '@angular/router';
     import { AuthService } from 'app/shared/services/auth.service';

     @Component({
     selector: 'app-signin',
      templateUrl: './signin.component.html',
      styleUrls: ['./signin.component.css']
      })
     export class SigninComponent implements OnInit {
     @ViewChild(MatProgressBar) progressBar: MatProgressBar;
     @ViewChild(MatButton) submitButton: MatButton;

     signinForm: FormGroup;

    constructor(
      private router: Router,
      private authService: AuthService) { }

    ngOnInit() {
      this.signinForm = new FormGroup({
      username: new FormControl('', Validators.required),
      password: new FormControl('', Validators.required),
      rememberMe: new FormControl(false)
      })
     }

     signin() {
      this.authService.login(this.signinForm.value).subscribe(
      (data) => localStorage.setItem('Token', data),
      (error) => console.log(error)
      ),
      function (complete){
      this.router.navigate(['/others'])
      this.authService.setLoggedIn(true)
       }

    }

    }

service.ts

      import { Injectable } from '@angular/core';
      import { HttpClient } from '@angular/common/http';
      import { environment } from 'environments/environment';
      import { Observable } from 'rxjs';

     @Injectable({
       providedIn: 'root'
     })
    export class AuthService {

     private loggedInStatus = JSON.parse(localStorage.getItem('loggedIn') || 
    'false')
     private baseUrl = environment.baseUrl
     private loginUrl = '/user/authenticate';

     constructor(private http: HttpClient) { }

     setLoggedIn(value: boolean){
      this.loggedInStatus = value
      localStorage.setItem('loggedIn', 'true')
      }

     get isLoggedIn(){
     return JSON.parse(localStorage.getItem('loggedIn') || 
     this.loggedInStatus.toString)
     }

我不知道如何在下面的登录函数中传递值

     login(): Observable<any>{
      const body = { }
     return this.http.post(this.baseUrl+this.loginUrl, body)
    }
    }

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    更新这个标签

    <mat-form-field class="full-width">
                  <input
                    type="username"
                    name="username"
                    matInput
                    [formControl]="signinForm.controls['username']"
                    placeholder="username"
                    value="">
    </mat-form-field>
    

    在您的服务中,您可以收到此值:

     login(form): Observable<any>{
      console.log(form); // this print an object {username: "anyemail@gmail.com", password: "mypasword", rememberMe: false}
      console.log(form.username);
      console.log(form.password);
      console.log(form.rememberMe);
      // Then you can send the parameters as requested by the API
      const body = { }
     return this.http.post(this.baseUrl+this.loginUrl, body)
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 2021-01-12
      • 2017-12-22
      • 1970-01-01
      • 2019-02-01
      • 2020-05-05
      • 2019-05-04
      相关资源
      最近更新 更多