Cannot read property 'get' of undefined in angular4 mean api - javascript

I am getting an error of Cannot read property 'get' of undefined TypeError: Cannot read property 'get'. Which needs to post some data from an endpoint to the table as illustrated on the example from the GitHub.
Here is the api service that I call the get method.
import { Injectable } from '#angular/core';
import { Http, Headers, Request, RequestOptions, RequestMethod, Response } from '#angular/http';
import 'rxjs/add/operator/map';
import { AuthService } from './auth.service';
import { environment } from '../../environments/environment';
#Injectable()
export class ApiService {
private baseUrl = environment.apiUrl;
constructor(private http:Http, private authService: AuthService) { }
get(url: string){
return this.request(url, RequestMethod.Get);
}
post(url: string, body: Object){
return this.request(url, RequestMethod.Post, body);
}
put(url: string, body: Object){
return this.request(url, RequestMethod.Put, body);
}
delete(url: string){
return this.request(url, RequestMethod.Delete);
}
request(url: string, method: RequestMethod, body?: Object){
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `Bearer ${this.authService.getToken()}`);
const requestOptions = new RequestOptions({
url: `${this.baseUrl}/${url}`,
method: method,
headers: headers
});
if(body){
requestOptions.body = body;
}
const request = new Request(requestOptions);
return this.http.request(request)
.map((res: Response) => res.json())
}
}
This is the exact line of code in another service that consume the api GET
staticQuery(): Observable<IUser[]> {
return this.api2.get('auth/account/users')
.map((res: Response) => {
return res.json();
});
}
Here is the complete code of the second service
import { Provider, SkipSelf, Optional, InjectionToken } from '#angular/core';
import { Response, Http } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { HttpInterceptorService, RESTService } from '#covalent/http';
import { ApiService } from '../../../../services/api.service';
import { AuthService } from '../../../../services/auth.service';
export interface IUser {
_id: string;
email:string;
createdAt: Date;
profile: {
name: string;
gender: string;
location: String;
picture: {
// data: Buffer;
contentType: string;
}
}
}
export class UserService extends RESTService<IUser> {
constructor(private _http: HttpInterceptorService, api: string,
private authService: AuthService,
private api2: ApiService) {
super(_http, {
baseUrl: api,
path: '/dashboard/users',
});
}
staticQuery(): Observable<IUser[]> {
return this.api2.get('auth/account/users')
.map((res: Response) => {
return res.json();
});
}
}
export const USERS_API: InjectionToken<string> = new InjectionToken<string>('USERS_API');
export function USER_PROVIDER_FACTORY(
parent: UserService, interceptorHttp: HttpInterceptorService, api: string,authService: AuthService,
api2: ApiService): UserService {
return parent || new UserService(interceptorHttp, api,authService,api2);
}
export const USER_PROVIDER: Provider = {
// If there is already a service available, use that. Otherwise, provide a new one.
provide: UserService,
deps: [[new Optional(), new SkipSelf(), UserService], HttpInterceptorService, USERS_API],
useFactory: USER_PROVIDER_FACTORY,
};
You can see all the code here for a previous question I had asked earlier here
My module
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { MatSnackBarModule, MatIconModule, MatListModule, MatTooltipModule, MatCardModule, MatButtonModule,
MatToolbarModule, MatInputModule, MatSlideToggleModule, MatMenuModule,MatSelectModule } from '#angular/material';
import { CovalentLoadingModule, CovalentDialogsModule, CovalentMediaModule, CovalentLayoutModule,
CovalentSearchModule, CovalentCommonModule } from '#covalent/core';
import { UsersComponent } from './users.component';
import { UsersFormComponent } from './form/form.component';
import { userRoutes } from './users.routes';
import { UserService, IUser, USER_PROVIDER, USERS_API } from './services/user.service';
import { MyaccountComponent } from './myaccount/myaccount.component';
import { AlluserComponent } from './allusers/allusers.component';
export { UsersComponent, UsersFormComponent, UserService, IUser, USER_PROVIDER, USERS_API };
import { ImageUploadModule } from "angular2-image-upload";
import { AuthService } from '../../../services/auth.service';
import { ApiService } from '../../../services/api.service';
#NgModule({
declarations: [
UsersComponent,
UsersFormComponent,
MyaccountComponent,
AlluserComponent
], // directives, components, and pipes owned by this NgModule
imports: [
// angular modules
CommonModule,
FormsModule,
RouterModule,
// material modules
MatSnackBarModule,
MatIconModule,
MatListModule,
MatTooltipModule,
MatCardModule,
MatButtonModule,
MatToolbarModule,
MatInputModule,
MatSlideToggleModule,
MatMenuModule,
MatSelectModule,
// MdFormFieldModule,
// covalent modules
CovalentLoadingModule,
CovalentDialogsModule,
CovalentMediaModule,
CovalentLayoutModule,
CovalentSearchModule,
CovalentCommonModule,
// extra
userRoutes,
ImageUploadModule.forRoot(),
], // modules needed to run this module
providers: [
{ provide: USERS_API, useValue: ''},
USER_PROVIDER,
AuthService,
ApiService,
],
})
export class UsersModule {}

Related

TypeError: Cannot read properties of undefined (reading 'subscribe') got error when try to run unit test

I have created a test case for my component with all dependency but when I execute the test case it shows error.
My unit test scenario is when form data is submitted formSubmit() method will be called and it send the data authservice there it makes an HTTP request and return some response. After that it navigate to another page.
Can anyone provide a solution for this test case??
Here are my code
login.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
// Services
import { ActivatedRoute, Router } from '#angular/router';
import { AuthService } from 'src/app/Service/auth.service';
// Material Component
import { MatSnackBar } from '#angular/material/snack-bar';
import { Title } from '#angular/platform-browser';
import { HttpErrorResponse } from '#angular/common/http';
import { LoginResponse } from '../../Model/auth';
import { duration, Notify } from '../../Model/notify';
import { NotificationComponent } from '../../shared/notification/notification.component';
import { NotifyService } from '../../Service/notify.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
constructor(
private documentTitle: Title,
private fb: FormBuilder,
private router: Router,
private route: ActivatedRoute,
private auth: AuthService,
private notify: NotifyService
) {}
passwordHide!: boolean;
returnUrl!: string;
pageTitle!: string;
loginForm!: FormGroup;
res!: LoginResponse;
ngOnInit(): void {
this.passwordHide = true;
this.pageTitle = 'Login | Online Shopping for Men & Women Shoes';
this.documentTitle.setTitle(this.pageTitle);
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '';
this.loginForm = this.fb.group({
username: ['', [Validators.required, Validators.minLength(8)]],
password: ['', [Validators.required, Validators.minLength(6)]],
});
}
/**
* send a request to auth service to make HTTP POST request
* if form is valid
*/
formSubmit() {
if (this.loginForm.valid) {
console.log(this.returnUrl);
this.auth.login(this.loginForm.value).subscribe({
next: (data: LoginResponse) => {
console.log(data);
this.res = data;
localStorage.setItem('access_token', data.accessToken);
this.auth.authStatusToggle(true);
this.router.navigateByUrl(this.returnUrl);
},
error: (error: HttpErrorResponse) => {
console.log(error);
if (error.status == 400) {
this.notify.warning(error.error.message);
} else {
this.notify.warning(error.error.message);
}
},
});
}
}
}
login.component.spec.ts
import { CommonModule } from '#angular/common';
import { ComponentFixture, TestBed, getTestBed } from '#angular/core/testing';
import {
FormBuilder,
FormsModule,
ReactiveFormsModule,
Validators,
} from '#angular/forms';
import { AppModule } from 'src/app/app.module';
import { AuthService } from 'src/app/Service/auth.service';
import { LoginComponent } from './login.component';
import * as Rx from 'rxjs';
import { Title } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
import {
HttpClientTestingModule,
HttpTestingController,
} from '#angular/common/http/testing';
import { LoginResponse } from 'src/app/Model/auth';
import { ActivatedRoute, Router } from '#angular/router';
import { RouterTestingModule } from '#angular/router/testing';
import { NotifyService } from 'src/app/Service/notify.service';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let authService = jasmine.createSpyObj('AuthService', ['login']);
let mockRouter = jasmine.createSpyObj('Router', ['navigate']);
let route: ActivatedRoute;
let documentTitle: Title;
let injector: TestBed;
let fb = new FormBuilder();
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [LoginComponent],
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
AppModule,
HttpClientModule,
HttpClientTestingModule,
RouterTestingModule,
],
providers: [
{ provide: FormBuilder, useValue: fb },
{ provide: AuthService, useValue: authService },
{ provide: Router, useValue: mockRouter },
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParams: {
returnUrl: '',
},
},
},
},
NotifyService,
Title,
],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
fixture.detectChanges();
component = fixture.componentInstance;
injector = getTestBed();
route = TestBed.get(ActivatedRoute);
documentTitle = injector.get(Title);
fb = TestBed.inject(FormBuilder);
component.passwordHide = true;
component.pageTitle = 'Login | Online Shopping for Men & Women Shoes';
documentTitle.setTitle(component.pageTitle);
component.returnUrl = route.snapshot.queryParams['returnUrl'] || '';
component.loginForm = fb.group({
username: ['', [Validators.required, Validators.minLength(8)]],
password: ['', [Validators.required, Validators.minLength(6)]],
});
});
it('should form submit successfully', () => {
// console.log(route.snapshot.queryParamMap.get('returnUrl'))
// console.log(component.returnUrl);
component.loginForm.get('username')?.setValue('ramkumar');
component.loginForm.get('password')?.setValue('Ramkumar#45');
expect(component.loginForm.valid).toBeTruthy();
authService.login.and.returnValue(
Rx.of({
accessToken: 'testToken',
username: 'test',
userId: 1,
} as LoginResponse)
);
component.formSubmit();
expect(component.res).toEqual({
accessToken: 'testToken',
username: 'test',
userId: 1,
} as LoginResponse);
expect(mockRouter.navigate).toHaveBeenCalledWith(['']);
});
});
auth.service.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
import { Observable, Subject } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Login, LoginResponse, Register } from '../Model/auth';
import { JwtHelperService } from '#auth0/angular-jwt';
import { UserResponse } from '../Model/user';
#Injectable({
providedIn: 'root',
})
export class AuthService {
private AUTH_API: string = environment.AUTH_API;
private USER_API: string = environment.USER_API;
public isUserLoggedIn: boolean = this.getAuthStatus();
private isLoggedIn: Subject<boolean> = new Subject<boolean>();
private token: any = localStorage.getItem('access_token')?.toString() || null;
private jwt: JwtHelperService;
/**
* Dependency Injections
* #param http
* #param route
*/
constructor(private http: HttpClient, private route: Router) {
this.jwt = new JwtHelperService();
this.isLoggedIn.subscribe((value) => {
console.log(value);
this.isUserLoggedIn = value;
});
}
/**
* Send user credentials to Auth API for create JWT token
* #param data
*/
login(data: Login): Observable<LoginResponse> {
return this.http.post<LoginResponse>(`${this.AUTH_API}/CreateToken`, data);
}
/**
* Send HTTP request to register new user
* #param data
*/
register(data: Register): Observable<UserResponse> {
return this.http.post<UserResponse>(`${this.USER_API}`, data);
}
/**
* Remove JWT token from localstorage to logout
*/
logout(): void {
localStorage.removeItem('access_token');
this.authStatusToggle(false);
if (this.getUserToken() == null) this.route.navigate(['login']);
}
/**
* get user JWT token from localstorage
* return token as string or null
*/
getUserToken(): string {
if (localStorage.getItem('access_token') != null) {
this.token = localStorage.getItem('access_token')?.toString() || null;
} else {
this.token = null;
}
return this.token;
}
authStatusToggle(value: boolean) {
this.isLoggedIn.next(value);
}
getAuthStatus(): boolean {
let token = localStorage.getItem('access_token')?.toString();
console.log(token);
if (token == null) {
return false;
}
return true;
}
}

Error: Can't resolve all parameters for LoginPage: ([object Object], [object Object], [object Object], ?)

I faced with next error and cannot understand how to resolve it.
Error: Can't resolve all parameters for LoginPage: ([object Object], [object Object], [object Object], ?).
I've checked almost every topic here and have tried multiple ways to resolve it but still can't beat it already second day.
Login.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams,AlertController } from 'ionic-angular';
import { AuthProvider } from '../../providers/auth/auth';
import { TabsPage } from '../tabs/tabs';
/**
* Generated class for the LoginPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
email:string = '';
password:string = '';
errorMsg:string;
constructor(
public navParams: NavParams,
public navCtrl: NavController,
public alertCtrl: AlertController
public authService: AuthProvider,
) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
errorFunc(message){
let alert = this.alertCtrl.create({
title: 'oops!',
subTitle: message,
buttons: ['OK']
});
alert.present();
}
myLogIn(){
if (this.email.trim() !=='' ) {
console.log(this.email.trim() + " " + this.password.trim() )
if (this.password.trim() === '') {
this.errorFunc('Please put your password')
}
else{
let credentials = {
email: this.email,
password: this.password
};
this.authService.login(credentials).then((result) => {
console.log(result);
this.navCtrl.setRoot(TabsPage);
}, (err) => {
console.log(err);
this. errorFunc('Wrong credentials ! try again')
console.log("credentials: "+JSON.stringify(credentials))
});
}
}
else{
this. errorFunc('Please put a vaild password ! for ex:(123456)')
}
}
myLogOut(){
this.authService.logout();
}
}
Auth.ts
import { Injectable } from '#angular/core';
import { Storage } from '#ionic/storage';
import { Http , Headers } from '#angular/http';
import { TabsPage } from '../../pages/tabs/tabs';
#Injectable()
export class AuthProvider {
rootPage:any = TabsPage;
public token:any;
constructor(public storage:Storage ,public http: Http) {
console.log('Hello AuthProvider Provider');
}
login(credentials){
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-type','application/json');
headers.append('X-Requested-With','XMLHttpRequest');
this.http.post('http://127.0.0.1:8000/api/auth/login', JSON.stringify(credentials), {
headers: headers})
.subscribe(res => {
let data = res.json();
this.token = data.token;
localStorage.setItem('token',data.access_token);
resolve(data);
}, (err) => {
reject(err);
}); });
}
checkAuthentication(){
return new Promise((resolve, reject) => {
this.storage.get('token').then((value) => {
this.token = value;
resolve(this.token)
})
});
}
logout(){
localStorage.setItem('token','');
}
}
app.moodule.ts
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { IonicStorageModule } from '#ionic/storage';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { LoginPage } from '../pages/login/login';
import { AddPage } from '../pages/add/add';
import { AuthProvider } from '../providers/auth/auth';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HttpModule } from '#angular/http';
import { ComplaintProvider } from '../providers/complaint/complaint';
#NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
LoginPage,
AddPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot(),
HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
LoginPage,
AddPage
],
providers: [
StatusBar,
SplashScreen,
AuthProvider,
ComplaintProvider,
{provide: ErrorHandler, useClass: IonicErrorHandler},
]
})
export class AppModule {}
You seem to be having a classic circular reference going around. You have the "TabsPage" imported in both Auth.ts & in your "LoginPage.ts".
A Classic Circular Reference.
Try removing the TabsPage from Auth.ts. In general, it is best if you have your components do very specific things so that you have a granular code and avoid such circular reference issues.

Angular 2 to latest - jsonp and URLSearchParams to HttpClient and HttpParams

I am trying to upgrade this to latest but getting error to display the data. i need to refactor from Jsonp to HttpClient, and HttpParams for below code. Any help would be great.
import { Injectable } from '#angular/core';
import {Jsonp, URLSearchParams} from '#angular/http';
import 'rxjs/Rx';
#Injectable()
export class MyService {
apikey: string;
constructor(private _jsonp: Jsonp) {
this.apikey = 'my_api_key';
console.log('it works');
}
getData() {
var search = new URLSearchParams();
search.set('sort_by','popularity.desc');
search.set('api_key', this.apikey);
return this._jsonp.get('url', {search})
.map(res => {
return res.json();
})
}
}
This should be able to fix your problem. Please check doc for more info
In you module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
In your service
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable()
export class MyService {
apikey: string;
constructor(private http: HttpClient){
this.apikey = 'my_api_key';
}
getData(): Observable<any> {
const params = new HttpParams()
.set('sort_by', popularity.desc)
.set('api_key', this.apikey);
return this.http.get('url', {params});
}
}

Angular 6 set withCredentials to true with every HttpClient call

If you want the credentials (cookie authentication token) to be passable through a call, you need to add { withCredentials: true } in your httpclient call. Something like this:
import { HttpClient } from '#angular/common/http';
...
constructor(private httpclient: HttpClient) { }
this.httpclient.get(url, { withCredentials: true })
I would just like to know if there is a way to preset { withCredentials: true } with every single call. I don't want to have to add { withCredentials: true } every time I make a call.
Here is a related question, but I am not sure if this works with HttpClient?
Create a HttpInterceptor:
#Injectable()
export class CustomInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
#NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor ,
multi: true
}
]
})
export class AppModule {}
You have two option here -
HttpInterceptor
auth.service.ts
If you are writing any standard application which require credential validation now or later then you will need AuthService. However you can ignore right now if you want.
// src/app/auth/auth.service.ts
import { Injectable } from '#angular/core';
import decode from 'jwt-decode';
#Injectable()
export class AuthService {
public getToken(): string {
return localStorage.getItem('token');
}
public isAuthenticated(): boolean {
// get the token
const token = this.getToken();
// return a boolean reflecting
// whether or not the token is expired
return tokenNotExpired(null, token);
}
}
app.module.ts
Provide HTTP_INTERCEPTORS which will intercept all request of yours.
// src/app/app.module.ts
import { HTTP_INTERCEPTORS } from '#angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor';
#NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
]
})
export class AppModule {}
token.interceptor.ts
This is Interceptor through which each HTTP request will pass through.
// src/app/auth/token.interceptor.ts
import { Injectable } from '#angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '#angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
Overwrite the standard HttpClient
app.module.ts
#NgModule({
providers: [ // expose our Services and Providers into Angular's dependency injection
{provide: HttpClient, useClass: ExtendedHttpService},
]
})
export class AppModule {
}
extended-http.service.ts
import {Injectable, Injector} from '#angular/core';
import {Request, XHRBackend, RequestOptions, Response, Http, RequestOptionsArgs, Headers} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import {Router} from '#angular/router';
import {AuthService} from './auth.service';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
#Injectable()
export class ExtendedHttpService extends HttpClient {
private router: Router;
private authService: AuthService;
constructor(backend: XHRBackend, defaultOptions: RequestOptions, private injector: Injector) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
if (typeof url === 'string') {
if (!options) {
options = {headers: new Headers()};
}
this.setHeaders(options);
} else {
this.setHeaders(url);
}
//console.log("url: " , url , ", Options:" , options);
return super.request(url, options).catch(this.catchErrors());
}
private catchErrors() {
return (res: Response) => {
if (this.router == null) {
this.router = this.injector.get(Router);
}
if (res.status === 401 || res.status === 403) {
//handle authorization errors
//in this example I am navigating to login.
console.log("Error_Token_Expired: redirecting to login.");
this.authService.logout();
}
return Observable.throw(res);
};
}
private setHeaders(objectToSetHeadersTo: Request | RequestOptionsArgs) {
if (this.authService == null) {
this.authService = this.injector.get(AuthService);
}
//add whatever header that you need to every request
//in this example I could set the header token by using authService that I've created
objectToSetHeadersTo.headers.set('Authorization', this.authService.getAuthToken());
}
}

Angular 4.3.3 : Why can't I get a DI in the Service

Before I ask, I do not speak English very well.
first, I'm #angular#4.3.3 and my typescript version is ~2.3.3
Ask.
I lazy loaded the LoginModule
AppRoute
import { RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login#LoginModule' }
];
export const AppRoutes = RouterModule.forRoot(routes);
and my
AppModule
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { AppRoutes } from './routing/app.routing';
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutes,
],
providers: [
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
and
LoginModule
import { CommonModule } from '#angular/common';
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { ErrorCodeService } from '../shared/service/error-code/error-code.service';
import { LoginService } from '../shared/service/login/login.service';
import { LoginComponent } from './login.component';
#NgModule({
imports: [
HttpClientModule,
CommonModule,
FormsModule,
RouterModule.forChild([
{ path: '', component: LoginComponent }
])
],
exports: [],
declarations: [ LoginComponent ],
providers: [
ErrorCodeService,
LoginService,
],
})
export class LoginModule { }
and
LoginService
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorCodeService } from '../error-code/error-code.service';
import { RequestCore } from '../request-core';
#Injectable()
export class LoginService extends RequestCore {
constructor(
protected http: HttpClient,
private errorCode: ErrorCodeService,
) {
super(http, '/Login');
}
public load(userid: string, passwd: string): Observable<any> {
const params = new HttpParams()
.append('id', userid)
.append('passwd', passwd);
return this.get({ params })
.map(res => {
if (res.islogin === 'true') {
return res.sendRedirect;
}
throw new Error(this.errorCode.getErrorMsg(res.reason));
});
}
}
RequestCore
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import { HttpOptions } from '../models';
export abstract class RequestCore {
constructor(
protected http: HttpClient,
private url: string,
) {
// 개발 모드에서는 proxy를 위해 url에 /dev 접두어를 붙인다.
if (environment.production === false) {
url = '/dev' + url;
}
}
protected get(options?: HttpOptions): Observable<any> {
return this.http.get(this.url, options);
}
protected post(options?: HttpOptions): Observable<any> {
return this.http.post(this.url, {}, options);
}
}
This is my error
I don't know why I can't DI in LoginService
ReuquestCore Are you making the wrong inheritance?
Teach me
Thank you!
Re:
An error occurs when the first screen is loaded.
When the next hmr is updated, no error occurs.

Categories

Resources