Angular2:JSON渲染

时间:2017-03-28 14:47:03

标签: angular

我是Angular 2的新用户,想要检查用户是否输入了正确的用户名和密码。

我附加了JSON格式。此外,我需要将值从一个组件传递到另一个组件。是否存在缓存除localstorage之外的值的任何功能。

gdb
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from '../login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [LoginService]
})
export class LoginComponent {
usernameModel: string;
passwordModel: string;
validLogin: Boolean;
loginData: any;
loginDataLength: number;
  constructor(private router: Router, private loginService: LoginService) { }

  homeNav(){

    this.loginService.getLoginData()
      .subscribe(data => {
        this.loginData = data;
        this.loginDataLength = data.length;
      });

      for(var i = 0; i < this.loginDataLength; i++)
      {
        if(this.loginData[i].username === this.usernameModel){
            console.log(this.loginData[i].username+', '+this.loginData[i].password);
        }
        else{
            console.log('Login issue');
        }
      };

  }
}

/* JSON

[{
	"username": "jay",
	"password": "jay",
	"userType": "standard"
}, {
	"username": "Admin",
	"password": "Admin",
	"userType": "admin"
}, {
	"username": "newuser",
	"password": "newuser",
	"userType": "standard"
}, {
	"username": "anonmyous",
	"password": "anonmyous",
	"userType": "standard"
}]

*/

2 个答案:

答案 0 :(得分:0)

您可以使用共享服务。

Here an official example on angular.io

答案 1 :(得分:0)

首先你必须等到getLoginData结算,其次不要把密码带到客户端:

   //... 

   constructor(private router: Router, private loginService: LoginService) { }

   ngOnInit(){

    this.loginService.getLoginData()
      .subscribe(data => {
        this.loginData = data;
        this.loginDataLength = data.length;
      });
  }
  homeNav(){
      for(var i = 0; i < this.loginDataLength; i++)
      {
        if(this.loginData[i].username === this.usernameModel){
            console.log(this.loginData[i].username+', '+this.loginData[i].password);
        }
        else{
            console.log('Login issue');
        }
      };

  }
}