我有一个名为" User"每个用户都有公司类型"公司"。
我试图对公司阵列进行更改,但我无法访问公司属性,这是我得到的错误:
authentication.service.ts (72,25): Property 'companies' does not exist on type 'User'.)
这是我的用户类:
import { Company } from './company';
export class User {
constructor(
public email:string,
public name:string,
public token:string,
public companies: Company[]
){
}
这是我公司的课程:
export class Company {
constructor(
public id:number,
public name:string,
public is_active:boolean
){}
}
我首先在下面的AuthService上设置用户,然后在使用" updateCompany"时收到错误。功能
import { Injectable } from '@angular/core';
import { User } from "../_models/user";
import { Observable } from 'rxjs/Rx';
import { Http, Headers, Response } from '@angular/http';
import { Router } from "@angular/router";
import 'rxjs/add/operator/map';
@Injectable()
export class AuthenticationService {
private user: User;
constructor(private http: Http,private router:Router) {
// set token if saved in local storage
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.user = currentUser;
}
login(email:string,password:string): Observable<boolean> {
const body = JSON.stringify({ email: email, password: password });
const headers = new Headers({
'Content-Type' : 'application/json'
});
return this.http.post("http://localhost:8000/api/v1/user/signin",body,{headers:headers})
.map(
(response: Response) => {
// login successful if there's a token in the response
let token = response.json() && response.json().token;
if(token){
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(response.json()));
// set user object
this.user = JSON.parse(localStorage.getItem('currentUser'));
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
//return response.json();
}
);
}
getUser(){
return this.user;
}
updateCompany(company_id){
console.log(this.user.companies);
}
}
更新: 这就是我如何调用updateCompany:
import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from '../../../../_services/index';
import { User } from "../../../../_models/user";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
private user: User;
constructor(
private authenticationService: AuthenticationService
) { }
ngOnInit() {
this.user = this.authenticationService.getUser();
}
changeCompany(company_id){
this.authenticationService.updateCompany(company_id);
}
onLogout(){
this.authenticationService.logout();
}
}