我正在使用API对用户和登录进行身份验证,但是我不知道如何保存服务器返回的令牌以用于将来的身份验证。返回的对象包含令牌。
import { Component, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms';
import {ServerService} from '../server.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private req: ServerService) { }
token = 'no';
ngOnInit() {
}
onSubmit(form: NgForm) {
this.req.requestLogin({'email': form.value.email,
'password': form.value.password})
.subscribe(
(response) => this.token = response.token, // ERROR
(error) => console.log(error)
);
}
}
显示的错误是“对象”类型上不存在属性“令牌”。
答案 0 :(得分:1)
请尝试以下代码。
import { Component, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms';
import {ServerService} from '../server.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private req: ServerService) { }
token = 'no';
ngOnInit() {
}
onSubmit(form: NgForm) {
this.req.requestLogin({'email': form.value.email,
'password': form.value.password})
.subscribe(
(response) => this.token = response['token'], // ERROR
(error) => console.log(error)
);
}
}
编辑1-
仅将response.token替换为response ['token']