Angular 7: Как получить данные из класса - PullRequest
0 голосов
/ 27 января 2019

Студент класс:

// Я получил класс ученика здесь (mock-student.ts)

export class Student {  
    id: string;  
    password: string;  
} 

Выше класс ученика (mock-student.ts)

import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';

import { Student } from '../student';
import { STUDENTS } from '../mock-students';
import { StudentService } from '../student.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private studentService: StudentService, private router: Router) { }

  student: Student[];

  id: string;
  password: string;

  ngOnInit() {
    this.getStudent();
  }

  login(): void {

    // I want to make a change here 
    if(this.id ==  '123' && this.password == '123') {
      this.router.navigate(["user"]);
    } else {
      alert("Invalid")
    }
  }

  getStudent(): void {
    this.studentService.getStudent()
    .subscribe(student => this.student = student);
  }
}

Выше мой LoginComponent.У меня вопрос: как я могу получить данные из класса Student и сделать так, чтобы данные могли войти на следующий маршрут?Спасибо, я надеюсь, вы все понимаете

login.component.html

<div fxLayout="column" fxLayoutAlign="space-around center">
  <mat-card class="login-card">
      <mat-card-header>
        <mat-card-title>Login</mat-card-title>
      </mat-card-header>

      <mat-card-content>
        <form class="login-form">
          <mat-form-field class="login-full-width">
            <input matInput placeholder="Matric Card Number" [(ngModel)]="id" name="id" required/>
          </mat-form-field>
            <mat-form-field class="login-full-width">
              <input matInput placeholder="Password" [(ngModel)]="password" type="password" name="password" required/>
          </mat-form-field>
        </form>
      </mat-card-content>

      <mat-card-actions align="end">    
        <button mat-raised-button (click)="login()" color="primary">Login</button>   
        <button mat-raised-button color="primary">Reset</button>
      </mat-card-actions>
  </mat-card>
</div>

Student.service.ts

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Student } from './student';
import { STUDENTS } from './mock-students';

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

  constructor() { }

  getStudents(): Observable<Student[]> {
    return of(STUDENTS);
  }
}

mock-student.ts

    import { Student } from './student';

export const STUDENTS: Student[] = [
    { id: 'AM1705002120', password: 'hisyam' },
    { id: 'AM1705002121', password: 'taca' },
    { id: 'AM1705002122', password: 'deena' },
    { id: 'AM1705002123', password: 'ucop' },
    { id: 'AM1705002124', password: 'ha' },
]

Ответы [ 2 ]

0 голосов
/ 27 января 2019

login.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

import { Student } from '../student';
import { StudentService } from '../student.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  student: Student;

  constructor(
     private studentService: StudentService,
     private router: Router,
     private location: Location
     ) { }


  id: string;
  password: string;

  ngOnInit() {
  }

  login(): void {

    this.studentService.getStudent(this.id, this.password)
      .subscribe( student => {
        this.router.navigate(["user"]); 
      }, err => alert(err));
  }
}

Student.service.ts

import { Injectable } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { Student } from './student';
import { STUDENTS } from './mock-students';

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

  getStudents(): Observable<Student[]> {
    return of(STUDENTS);
  }
  
  getStudent(id: string, password: string): Observable<Student> {
    const student = STUDENTS.filter( s => s.id === id && s.password === password);

    if (student.length === 1) {
       return of(student[0]);
    }
    
    return throwError('Invalid');
  }
}
0 голосов
/ 27 января 2019

Удалите код из ngOnInit и вызовите службу внутри метода входа в систему.

login(): void {

  this.studentService.getStudent()
    .subscribe( student => {
        const result = student.filter( s => this.id === s.id && this.password === s.password);
     
        if (result.length > 0) {
          this.router.navigate(["user"]);
          return;
        }
        alert("Invalid");
      });    
}

Но будьте осторожны, это действительно небезопасный код.Вы должны передать вызов API для аутентификации студента, а затем получить токен и т. Д. И т. Д. И т. Д.

  login(): void {
    this.studentService.getStudent(this.id, this.password)
      .subscribe( s => {
        this.router.navigate('[user]');
      }, error => {
        alert('Invalid' + error.message);
      });
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...