Error: NG0204: Can't resolve all parameters for NzModalRef: (?, ?, ?) - javascript

I'm doing an angular project using the NZ-Zorro library and I'm having a hard time finding what are these parameters that aren't being solved from NzModalRef, when I try to run the test --code-coverage to do the tests. I get this error.
Error: NG0204: Can't resolve all parameters for NzModalRef: (?, ?, ?).
That's my .spec
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { MinistryService } from './../../ministry.service';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import {
NzModalModule,
NzModalService,
NzModalRef,
} from 'ng-zorro-antd/modal';
import { MembersService } from '../../members.service';
import { ComponentFixture } from '#angular/core/testing';
import {
HttpClientTestingModule,
HttpTestingController,
} from '#angular/common/http/testing';
import {
UntypedFormBuilder,
UntypedFormGroup,
Validators,
FormsModule,
} from '#angular/forms';
import { TestBed } from '#angular/core/testing';
import { HttpClient } from '#angular/common/http';
import { FormNewMemberComponent } from './form-new-member.component';
import { ReactiveFormsModule } from '#angular/forms';
describe('FormNewMemberComponent', () => {
let component: FormNewMemberComponent;
let fixture: ComponentFixture<FormNewMemberComponent>;
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
let fb: UntypedFormBuilder;
let validateForm: UntypedFormGroup;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FormNewMemberComponent],
imports: [
HttpClientTestingModule,
ReactiveFormsModule,
NzModalModule,
FormsModule,
BrowserAnimationsModule,
],
providers: [
MembersService,
NzModalService,
HttpClient,
Validators,
NzModalRef,
MinistryService,
NzNotificationService,
UntypedFormBuilder,
],
}).compileComponents();
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
fb = TestBed.inject(UntypedFormBuilder);
fixture = TestBed.createComponent(FormNewMemberComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
My .ts
import { NzModalRef } from 'ng-zorro-antd/modal';
import { Ministry } from './../../ministry/ministry.model';
import { MemberPageComponent } from './../member-page.component';
import { MembersService } from '../../members.service';
import { Component, OnInit } from '#angular/core';
import {
UntypedFormBuilder,
UntypedFormControl,
UntypedFormGroup,
Validators,
} from '#angular/forms';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { MinistryService } from '../../ministry.service';
#Component({
selector: 'app-form-new-member',
templateUrl: './form-new-member.component.html',
styleUrls: ['./form-new-member.component.scss'],
})
export class FormNewMemberComponent implements OnInit {
validateForm!: UntypedFormGroup;
isVisible = false;
pagina!: MemberPageComponent;
members: any;
ministrys: Ministry[] = []
listOfMinistrys!: Ministry[]
createNotificationSuccess(type: string): void {
this.notification.create(
type,
'Sucesso!',
'Membro adicionado.',
{nzDuration: 2000}
);
}
createNotificationError(type: string): void {
this.notification.create(
type,
'Erro!',
'Membro não foi adicionado.',
{nzDuration: 2000}
);
}
constructor(
private fb: UntypedFormBuilder,
private membersService: MembersService,
private nzModalRef: NzModalRef,
private notification: NzNotificationService,
private ministryService: MinistryService
) {}
ngOnInit(): void {
this.validateForm = this.fb.group({
email: [null, [Validators.email, Validators.required]],
password: [null, [Validators.required]],
checkPassword: [null, [Validators.required, this.confirmationValidator]],
name: [null, [Validators.required]],
phoneNumber: [null, [Validators.required]],
cpf: [null, [Validators.required]],
rg: [null, [Validators.required]],
ministry: [null, [Validators.required]],
address: [null, [Validators.required]],
});
this.showMinistry()
}
submitForm(): void {
if (this.validateForm.valid) {
this.membersService.create(this.validateForm.value).subscribe(
(success) => {
this.createNotificationSuccess('success')
this.destroyModal();
},
(error) => {
this.createNotificationError('error')
}
);
} else {
Object.values(this.validateForm.controls).forEach((control) => {
if (control.invalid) {
control.markAsDirty();
control.updateValueAndValidity({ onlySelf: true });
}
});
}
}
updateConfirmValidator(): void {
Promise.resolve().then(() =>
this.validateForm.controls['checkPassword'].updateValueAndValidity()
);
}
confirmationValidator = (
control: UntypedFormControl
): { [s: string]: boolean } => {
if (!control.value) {
return { required: true };
} else if (control.value !== this.validateForm.controls['password'].value) {
return { confirm: true, error: true };
}
return {};
};
destroyModal(): void {
this.nzModalRef.destroy({ newMember: this.validateForm.value });
}
showMinistry(){
this.ministryService.getMinistrys().subscribe((data) => {
this.ministrys = data;
this.listOfMinistrys = [...this.ministrys];
});
}
}
My service
import { Injectable } from '#angular/core';
import { Member } from './member-page/members.model';
import { Observable, take} from 'rxjs';
import { HttpClient } from '#angular/common/http';
const apiMembers = 'http://localhost:3000/membrosBd';
#Injectable({
providedIn: 'root',
})
export class MembersService {
constructor(private http: HttpClient) { }
getMembers(): Observable<Member[]> {
return this.http.get<Member[]>(apiMembers)
}
create(member: Member): Observable<Member>{
return this.http.post<Member>(apiMembers, member).pipe(take(1));
}
}
And my module
import { NzNotificationModule } from 'ng-zorro-antd/notification';
import { HttpClientModule } from '#angular/common/http';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { NzPaginationModule } from 'ng-zorro-antd/pagination';
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { MemberPageComponent } from './member-page/member-page.component';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzAutocompleteModule } from 'ng-zorro-antd/auto-complete';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzDropDownModule } from 'ng-zorro-antd/dropdown';
import { NzModalModule, NzModalRef } from 'ng-zorro-antd/modal';
import { FormNewMemberComponent } from './member-page/form-new-member/form-new-member.component';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { MinistryComponent } from './ministry/ministry.component';
import { NzListModule } from 'ng-zorro-antd/list';
#NgModule({
declarations: [
MemberPageComponent,
FormNewMemberComponent,
MinistryComponent,
],
imports: [
CommonModule,
NzTableModule,
NzPaginationModule,
NzAutocompleteModule,
NzButtonModule,
NzInputModule,
NzIconModule,
NzDropDownModule,
ReactiveFormsModule,
HttpClientModule,
FormsModule,
NzModalModule,
NzFormModule,
NzSelectModule,
NzNotificationModule,
NzListModule,
],
providers: [NzModalRef],
exports: [
MemberPageComponent
]
})
export class MembrosModule { }
I thank anyone who can help me.
hope that the nzmodalref parameters can be solved

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;
}
}

Angular fetching apis

My apis is http://dradiobeats.x10host.com/public/api/areas
my app.component.ts:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { Post } from './post.model';
import { PostsService } from './posts.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
loadedPosts: Post[] = [];
isFetching = false;
error = null;
private errorSub: Subscription;
constructor(private http: HttpClient, private postsService: PostsService) {}
ngOnInit() {
this.errorSub = this.postsService.error.subscribe(errorMessage => {
this.error = errorMessage;
});
this.isFetching = true;
this.postsService.fetchPosts().subscribe(
posts => {
this.isFetching = false;
this.loadedPosts = posts;
},
error => {
this.isFetching = false;
this.error = error.message;
}
);
}
onCreatePost(postData: Post) {
// Send Http request
this.postsService.createAndStorePost( postData.id, postData.name, postData.domain, postData.description , postData.picture);
}
onFetchPosts() {
// Send Http request
this.isFetching = true;
this.postsService.fetchPosts().subscribe(
posts => {
this.isFetching = false;
this.loadedPosts = posts;
},
error => {
this.isFetching = false;
this.error = error.message;
console.log(error);
}
);
}
onClearPosts() {
// Send Http request
this.postsService.deletePosts().subscribe(() => {
this.loadedPosts = [];
});
}
onHandleError() {
this.error = null;
}
ngOnDestroy() {
this.errorSub.unsubscribe();
}
}
my posts.service.ts
import { Injectable } from '#angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpEventType
} from '#angular/common/http';
import { map, catchError, tap } from 'rxjs/operators';
import { Subject, throwError } from 'rxjs';
import { Post } from './post.model';
#Injectable({ providedIn: 'root' })
export class PostsService {
error = new Subject<string>();
constructor(private http: HttpClient) {}
createAndStorePost( id: string,
name: string,
description: string,
domain: string,
picture: any ) {
const postData: Post = { id , domain , name, description, picture };
this.http
.post<{ name: string , description: string , domain: string , picture: string }>(
'http://dradiobeats.x10host.com/api/areas',
postData,
{
observe: 'response'
}
)
.subscribe(
responseData => {
console.log(responseData);
},
error => {
this.error.next(error.message);
}
);
}
fetchPosts() {
let searchParams = new HttpParams();
searchParams = searchParams.append('print', 'pretty');
searchParams = searchParams.append('custom', 'key');
return this.http
.get<{ [key: string]: Post}>(
'http://dradiobeats.x10host.com/api/areas',
{
headers: new HttpHeaders({ 'Custom-Header': 'Hello' }),
params: searchParams,
responseType: 'json'
}
)
.pipe(
map(responseData => {
const postsArray: Post[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
postsArray.push({ ...responseData[key], id: key });
}
}
return postsArray;
}),
catchError(errorRes => {
// Send to analytics server
return throwError(errorRes);
})
);
}
deletePosts() {
return this.http
.delete('http://dradiobeats.x10host.com/api/areas', {
observe: 'events',
responseType: 'text'
})
.pipe(
tap(event => {
console.log(event);
if (event.type === HttpEventType.Sent) {
// ...
}
if (event.type === HttpEventType.Response) {
console.log(event.body);
}
})
);
}
}
my posts.model.ts
export interface Post {
id: string;
name: string;
domain: string;
description: string;
picture: any;
}
my logging-interceptor.service.ts
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEventType
} from '#angular/common/http';
import { tap } from 'rxjs/operators';
export class LoggingInterceptorService implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
console.log('Outgoing request');
console.log(req.url);
console.log(req.headers);
return next.handle(req).pipe(
tap(event => {
if (event.type === HttpEventType.Response) {
console.log('Incoming response');
console.log(event.body);
}
})
);
}
}
my auth-interceptor.service.ts
import {
HttpInterceptor,
HttpRequest,
HttpHandler
} from '#angular/common/http';
export class AuthInterceptorService implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modifiedRequest = req.clone({
headers: req.headers.append('Auth', 'xyz')
});
return next.handle(modifiedRequest);
}
}
my app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
my app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { AppComponent } from './app.component';
import { AuthInterceptorService } from './auth-interceptor.service';
import { LoggingInterceptorService } from './logging-interceptor.service';
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: LoggingInterceptorService,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptorService,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
my app.component.spec.ts
import { TestBed, async } from '#angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'ng-complete-guide-update'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('ng-complete-guide-update');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-complete-guide-update!');
});
});
my app.component.html
import { TestBed, async } from '#angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'ng-complete-guide-update'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('ng-complete-guide-update');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-complete-guide-update!');
});
});
my app.component.css
.container {
margin-top: 30px;
}
.row {
margin: 20px 0;
}
I am only getting data not elements [id ,name,description,domain,picture]why??

Error: Trying to get the AngularJS injector before it being set

I am testing an angular 7 component that uses angular js components inside.
I am using jasmine and karma for testing.
I am getting
Angular Hybrid - **Error: Trying to get the AngularJS injector before it being set.** when I am running the ng test my-app-name.
app-module-ts -
import { BrowserModule } from '#angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '#angular/core';
import { UpgradeModule, downgradeComponent } from '#angular/upgrade/static';
import { AppComponent } from './app.component';
import { BusyOverlayModule } from '../../../app-shared/src/lib/busy-overlay/busy-overlay.module';
import { L10nTranslationModule } from '../../../app-shared/src/lib/l10n-translation/l10n-translation.module';
import { LocalizationService } from '../../../app-shared/src/lib/l10n-translation/localization.service';
import { WatchlistModule } from './watchlist/watchlist.module';
import oprRtsmViewPickerModuleName
from '../../../../../../shared/shared-html/js/directives/oprRtsmViewPicker/oprRtsmViewPicker.module.js';
import oprTableFooterModuleName
from '../../../../../../shared/shared-html/js/directives/oprTableFooter/oprTableFooter.module.js';
import oprContextPanelModuleName
from '../../../../../../shared/shared-html/js/directives/oprContextPanel/oprContextPanel/oprContextPanel.module.js';
import { FilterFactory } from 'angular';
import oprPopupServiceModuleName from '../../../../../../shared/shared-html/js/services/oprPopup.service';
import ciContextDataServiceModuleName from '../../../../../../shared/shared-html/js/services/ciContextData.service';
import watchlistOptionsLauncherComponent from './watchlist/options-menu/watchlistOptionsLauncherNg1';
import oprLocalizationUtil from '../../../../../../shared/shared-html/js/utils/oprLocalizationUtil';
import appConstantsUtil from '../../../../../../shared/shared-html/js/utils/appConstantsUtil';
import { setAngularJSGlobal } from '#angular/upgrade/static';
import { oprContextPanelApiServiceProvider } from '../../../ng1-adapters/adapters/opr-conext-panel-api-provider';
import { ciContextDataServiceProvider } from '../../../ng1-adapters/adapters/opr-conext-data-api-provider';
import { Oprl10nPipe } from '../../../app-shared/src/lib/l10n-translation/oprl10n.pipe';
declare const angular: angular.IAngularStatic;
setAngularJSGlobal(angular);
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
UpgradeModule,
BusyOverlayModule,
L10nTranslationModule,
WatchlistModule
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: onAppInit,
multi: true
},
oprContextPanelApiServiceProvider,
ciContextDataServiceProvider,
Oprl10nPipe
],
entryComponents: [
AppComponent
]
})
export class AppModule {
constructor(private upgrade: UpgradeModule, private localizationService: LocalizationService) { }
/**
* bootstrap hybrid AngularJS/Angular application with downgraded root Angular component
*/
ngDoBootstrap() {
const ng1L10nfilterFactory: angular.Injectable<FilterFactory> = function () {
return (key) => {
return oprLocalizationUtil.getLocalizedString(key);
};
};
const ng1RootModule = angular.module('ng1-root', [
oprPopupServiceModuleName,
oprRtsmViewPickerModuleName,
oprTableFooterModuleName,
oprContextPanelModuleName,
ciContextDataServiceModuleName
]).directive('oprRoot', downgradeComponent({component: AppComponent})).filter('oprL10n', ng1L10nfilterFactory)
.component('oprOptionsMenuLauncher', watchlistOptionsLauncherComponent);
this.localizationService.setOprLocalizeUtilObj(oprLocalizationUtil);
this.upgrade.bootstrap(document.body, [ng1RootModule.name], {strictDi: false});
}
}
export function onAppInit(): () => Promise<any> {
return (): Promise<any> => {
return new Promise((resolve, reject) => {
const appConstants = appConstantsUtil.appConstants;
/**
* For Testing, Replace this appConstants.locale.toLowerCase() code with en
*/
oprLocalizationUtil.init(appConstants.locale.toLowerCase(), appConstants.staticContext, [
'opr-watchlist',
'opr-common'
], function () {
resolve(true);
});
});
};
}
app.component.ts -
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'opr-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
showBusyOverlay:boolean = true;
ngOnInit() {
this.showBusyOverlay = false;
}
}
app.component.spec.ts -
import { TestBed, ComponentFixture, async } from '#angular/core/testing';
import * as angular from '#angular/upgrade/src/common/angular1';
import { UpgradeModule, setAngularJSGlobal } from '#angular/upgrade/static';
import { AppComponent } from './app.component';
import { AppSharedModule } from "../../../app-shared/src/lib/app-shared.module";
import { WatchlistComponent } from './watchlist/watchlist.component';
import { WatchlistFooterComponent } from './watchlist/watchlist-footer/watchlist-footer.component';
import { WatchlistHeaderComponent } from './watchlist/watchlist-header/watchlist-header.component';
import { WatchlistCardsComponent } from './watchlist/watchlist-cards/watchlist-cards.component';
import { WatchlistCardComponent } from "./watchlist/watchlist-cards/watchlist-card/watchlist-card.component";
import { WatchlistCardsModule } from './watchlist/watchlist-cards/watchlist-cards.module';
import { WatchlistModule } from './watchlist/watchlist.module';
import { ContextPanelApi } from 'shared/directives/oprContextPanel/oprContextPanel/oprContextPanelApi.service';
import { CiContextDataService } from '../../../../../../shared/shared-html/js/services/ciContextData.service';
import { CiContextMenuService } from '../../../app-shared/src/lib/ci-context-menu.service';
import { HttpClientModule, HttpClientXsrfModule } from '#angular/common/http';
import { Ng1AdaptersModule } from '../../../ng1-adapters/ng1-adapters.module';
import { FormsModule } from '#angular/forms';
import { BusyOverlayModule } from '../../../app-shared/src/lib/busy-overlay/busy-overlay.module';
import { L10nTranslationModule } from '../../../app-shared/src/lib/l10n-translation/l10n-translation.module';
import '../../../../../../shared/shared-html/test/config/index-mock.js';
import { Oprl10nPipe } from "../../../app-shared/src/lib/l10n-translation/oprl10n.pipe";
import { of } from 'rxjs';
export class MockBusyOverlayModule {
}
export class MockContextPanelApi {
}
export class MockCiContextDataService {
}
export class MockCiContextMenuService {
}
export class Oprl10nPipeStub {
public get(key: any): any {
return of(key);
}
public transform(key: any): any {
return of(key);
}
}
setAngularJSGlobal(angular);
describe('AppComponent', () => {
window['getAppConstants'] = function () {
return JSON.stringify({
topazWebContext: "",
mashupParams: { uim_sourceId: "0" },
staticContext: "/base",
locale: "en-us",
oprWebContext: ""
});
};
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
UpgradeModule,
BusyOverlayModule,
HttpClientModule,
AppSharedModule,
// appConstantsUtil,
// WatchlistModule,
Ng1AdaptersModule,
L10nTranslationModule,
// WatchlistModule
// WatchlistCardsModule
],
providers: [
{ provide: Oprl10nPipe, useClass: Oprl10nPipeStub },
// { provide: BusyOverlayModule, useClass: MockBusyOverlayModule }
{ provide: ContextPanelApi, useClass: MockContextPanelApi },
{ provide: CiContextDataService, useClass: MockCiContextDataService },
{ provide: CiContextMenuService, useClass: MockCiContextMenuService },
// { provide: appConstantsUtil }
],
declarations: [
AppComponent,
WatchlistComponent,
WatchlistFooterComponent,
WatchlistHeaderComponent,
WatchlistCardComponent,
WatchlistCardsComponent
]
// imports: [
// WatchlistModule
// ]
}).compileComponents();
}));
beforeEach(() => {
window['getAppConstants'] = function () {
return JSON.stringify({
topazWebContext: "",
mashupParams: { uim_sourceId: "0" },
staticContext: "/base",
locale: "en-us",
oprWebContext: ""
});
};
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the app', () => {
expect(component).toBeTruthy();
});
});
My angular js version is 1.6 and Angular 7, as I said I am testing angular 7 components that use angular js components.
I found some links on web -
Angular Hybrid Error: Trying to get the AngularJS injector before it being set
https://github.com/angular/angular/issues/23141
but no help. I am not able to find anything in the angular doc as well.
Please guide.
I solved this by adding
const upgrade = TestBed.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document);
const serviceWhichReliesonInjector =
to my beforeEach Method.
afterwards i could simply access the service by
TestBed.get(ServiceWhichReliesonInjector)

Angular StaticInjectorError

Hi im new working with angular so im following a youtube tutorial to build a chat.
This project on owners github-> https://github.com/wesdoyle/base-chat
I tried to add AngularFireDatabase to providers its still not working.
I don't know why i get this error when i try to login.
That's my app.module.ts file:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { ChatFormComponent } from './chat-form/chat-form.component';
import { ChatroomComponent } from './chatroom/chatroom.component';
import { FeedComponent } from './feed/feed.component';
import { MessageComponent } from './message/message.component';
import { LoginFormComponent } from './login-form/login-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { NavbarComponent } from './navbar/navbar.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserItemComponent } from './user-item/user-item.component';
import { ChatService } from './services/chat.service';
import { AuthService } from './services/auth.service';
import { appRoutes } from '../routes';
import { environment } from '../environments/environment';
#NgModule({
declarations: [
AppComponent,
ChatFormComponent,
ChatroomComponent,
FeedComponent,
MessageComponent,
LoginFormComponent,
SignupFormComponent,
NavbarComponent,
UserListComponent,
UserItemComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
FormsModule,
AngularFireModule,
AngularFireDatabaseModule,
AngularFireAuthModule,
AngularFireModule.initializeApp(environment.firebase)
],
providers: [AuthService,ChatService],
bootstrap: [AppComponent]
})
export class AppModule { }
And that's the login-form.component.ts where i throw the error.
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { AngularFireDatabase} from 'angularfire2/database';
import { Router } from '#angular/router';
#Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent {
email: string;
password: string;
errorMsg: string;
constructor(private authService: AuthService, private router: Router) { }
login() {
console.log('login() called from login-form component');
this.authService.login(this.email, this.password)
.catch(error => this.errorMsg = error.message);
}
}
This is the chat.service.ts:
import { Injectable } from '#angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable,of } from 'rxjs';
import { AuthService } from '../services/auth.service';
import * as firebase from 'firebase/app';
import { ChatMessage } from '../models/chat-message.model';
#Injectable()
export class ChatService {
user: firebase.User;
chatMessages: FirebaseListObservable<ChatMessage[]>;
chatMessage: ChatMessage;
userName: Observable<string>;
constructor(
private db: AngularFireDatabase,
private afAuth: AngularFireAuth
) {
this.afAuth.authState.subscribe(auth => {
if (auth !== undefined && auth !== null) {
this.user = auth;
}
this.getUser().subscribe(a => {
this.userName = a.displayName;
});
});
}
getUser() {
const userId = this.user.uid;
const path = `/users/${userId}`;
return this.db.object(path);
}
getUsers() {
const path = '/users';
return this.db.list(path);
}
sendMessage(msg: string) {
const timestamp = this.getTimeStamp();
const email = this.user.email;
this.chatMessages = this.getMessages();
this.chatMessages.push({
message: msg,
timeSent: timestamp,
userName: this.userName,
email: email });
}
getMessages(): FirebaseListObservable<ChatMessage[]> {
// query to create our message feed binding
return this.db.list('messages', {
query: {
limitToLast: 25,
orderByKey: true
}
});
}
getTimeStamp() {
const now = new Date();
const date = now.getUTCFullYear() + '/' +
(now.getUTCMonth() + 1) + '/' +
now.getUTCDate();
const time = now.getUTCHours() + ':' +
now.getUTCMinutes() + ':' +
now.getUTCSeconds();
return (date + ' ' + time);
}
}
In your chart.service.ts you have a wrong import which is depreciated,
Change
From
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database-deprecated';
To
import { AngularFireDatabase,FirebaseListObservable,FirebaseObjectObservable } from 'angularfire2/database';
You forgot to provide your service in the Component
#Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css'],
providers: [AuthService]
})
hope this helps.

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