Angular2和Web API会话控制

时间:2017-03-16 09:41:44

标签: html sql angular session asp.net-web-api

我正在做登录服务。但我只能登录,但我想建立一个会话来控制登录。 我的login.component.ts在哪里:

 @Component({
    selector: 'login',
    templateUrl: './app/login/login.component.html'
 })

export class LoginComponent implements OnInit {
   model: any = {};
   loading = false;
   returnUrl: string;

constructor(
    private route: ActivatedRoute,
    private router: Router,
    private utilizadorService: UtilizadoresService,
    private alertService: AlertService) { }

ngOnInit() {
    // reset login status
    this.utilizadorService.logout();
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}

login() {
    console.log("Login! ");
    this.loading = true;
    this.utilizadorService.login(this.model.email, this.model.password).subscribe(
        data => {
            this.alertService.success('Login successful', true);
            this.router.navigate(['/profile']);
        },
        error => {
            this.alertService.error(error._body);
            this.loading = false;
        });
}
}

并且有我的utilizadores.serice.ts,其中是登录/注册函数:

@Injectable()
export class UtilizadoresService {

constructor(private _http: Http) {}

private RegenerateData = new Subject<number>();
// Observable string streams
RegenerateData$ = this.RegenerateData.asObservable();

AnnounceChange(mission: number) {
    this.RegenerateData.next(mission);
}

LoadData(): Promise<IUtilizadores[]> {
    return this._http.get('/api/utilizadores')
        .toPromise()
        .then(response => this.extractArray(response))
        .catch(this.handleErrorPromise);
}

Add(model: IUtilizadores) {
    let headers = new Headers({
        'Content-Type':
        'application/json; charset=utf-8'
    });
    let options = new RequestOptions({ headers: headers });
    delete model["id"];
    let body = JSON.stringify(model);
    return this._http.post('/api/utilizadores/', body, options).toPromise().catch(this.handleErrorPromise);
}

Update(model: IUtilizadores) {
    let headers = new Headers({
        'Content-Type':
        'application/json; charset=utf-8'
    });
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(model);
    return this._http.put('/api/utilizadores/', body, options).toPromise().catch(this.handleErrorPromise);
}

Delete(id: number) {
    return this._http.delete('/api/utilizadores/?id=' + id).toPromise().catch(this.handleErrorPromise);
}

login(email: string, password: string) {
    return this._http.post('/api/utilizadores/login', { email: email, password: password })
        .map((response: Response) => {
            let utilizador = response.json();
            if (utilizador) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(utilizador));  
            }
        });
}

logout() {
    // remove user from local storage to log user out
    // localStorage.removeItem('id_token');
    localStorage.removeItem('currentUser');
}

public authenticated() {
    // Check if there's an unexpired JWT
    // This searches for an item in localStorage with key == 'id_token'
    return tokenNotExpired();
}

protected extractArray(res: Response, showprogress: boolean = true) {
    let data = res.json();

    return data || [];
}

protected handleErrorPromise(error: any): Promise<void> {
    try {
        error = JSON.parse(error._body);
    } catch (e) {
    }

    let errMsg = error.errorMessage
        ? error.errorMessage
        : error.message
            ? error.message
            : error._body
                ? error._body
                : error.status
                    ? `${error.status} - ${error.statusText}`
                    : 'unknown server error';

    console.error(errMsg);
    return Promise.reject(errMsg);
}
}
export interface IUtilizadores {
id: number,
email: string,
nickname: string,
password: string
}

我正在为一个学校项目做这个,所以我不想使用Auth0,我正在使用VS 2015和微软SQL服务器

0 个答案:

没有答案