Я запустил новый проект Angular 6 и решил попробовать новую команду ng generate library
.
«Основной» функцией этой библиотеки является сервис:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthResponseModel } from "./auth-response.model";
import { catchError, map } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import decode from 'jwt-decode'
@Injectable()
export class AuthService {
private authURL: string = "http://localhost:8090/oauth/token";
private loginPath : string = "/login";
isLoggedIn: boolean = false;
redirectURL: string;
public isRefreshing : boolean = false;
constructor(private http: HttpClient) {
this.redirectURL = "";
this.isLoggedIn = this.getToken() != null;
}
login(user: string, password: string): Observable<boolean> {
var data = new FormData();
data.append("grant_type", "password");
data.append("username", user);
data.append("password ", password);
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + window.btoa("web:secret")
})
};
return this.http.post<AuthResponseModel>(this.authURL, data, httpOptions)
.pipe(
map((r: AuthResponseModel) => {
if (r.access_token) {
localStorage.setItem("access_token", r.access_token);
localStorage.setItem("refresh_token", r.refresh_token);
this.isLoggedIn = true;
return true;
}
}
));
};
refresh() : Observable<any> {
var data = new FormData();
this.isRefreshing = true;
data.append("grant_type", "refresh_token");
data.append("refresh_token", this.getRefreshToken());
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + window.btoa("web:secret")
})
};
return this.http.post<AuthResponseModel>(this.authURL, data, httpOptions)
.pipe(
map( r => {
console.log("Old token" + this.getToken());
localStorage.setItem("access_token", r.access_token);
localStorage.setItem("refresh_token", r.refresh_token);
this.isLoggedIn = true;
this.isRefreshing = false;
console.log("New token" + r.access_token);
return r.access_token;
})
)
}
logout(): void {
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
this.isLoggedIn = false;
}
checkTokenExpired(checkRefresh = false) : boolean {
if(checkRefresh) { return decode(this.getRefreshToken()).exp < (Date.now().valueOf() / 1000); }
return decode(this.getToken()).exp < (Date.now().valueOf() / 1000);
}
getToken(): string {
return localStorage.getItem("access_token");
}
getRefreshToken() : string {
return localStorage.getItem('refresh_token');
}
}
На основании кода шаблона, сгенерированного ng generate library
, мой public_api.ts
код выглядит следующим образом:
/*
* Public API Surface of auth-lib
*/
export * from './lib/auth-lib.service';
export * from './lib/auth-interceptor';
export * from './lib/auth-response.model';
Однако каждый раз, когда я пытаюсь вставить его в @Component
.
import { Component, OnInit } from '@angular/core';
import { AuthService } from 'auth-lib';
import { Router } from '@angular/router';
import {Injectable} from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
user : string;
pass : string;
constructor(private authService : AuthService, private router : Router) {
this.user = "";
this.pass = "";
}
, я получаю следующее:
[Angular] Can't resolve all parameters for LoginComponent
.
Проблемасвязано с инъекцией AuthService
(удаление ее устраняет ошибку).Я ссылался на несколько вопросов о StackOverflow (включая this , this и this );однако, кажется, что резолюции вращаются вокруг «бочек» и забывают аннотацию @Injectable
.Поэтому я не уверен, как применять такие решения к моей проблеме.
Любой совет будет принят.
Спасибо.
РЕДАКТИРОВАТЬ:
Интересно, что если я изменю оператор импорта с import { AuthService } from 'auth-lib'
на import { AuthService } from 'projects/auth-lib/src/public_api';
, он сработает, но на самом деле это нежелательно.