I want to store array of items in a service (called cart service) and show it in component (cart.component.ts).
but the items are chosen each alone by the component bgview.component.ts that is a children of component single.component.ts that receive the items through http requests.
when i open the cart component i receive an empty array.
can i store these items in the service without losing them when navigating.
i've tried the following steps:
The component that i want to send items from :
export class BgviewComponent implements OnInit {
#Input() item: Item;
constructor(private cartservice: CartService) { }
ngOnInit() {
}
onAddToCart(){
this.cartservice.items.push(this.item);
}
}
the service :
#Injectable({
providedIn: 'root',
})
export class CartService {
public items: Item[]=[];
}
the receiving component:
export class CartComponent implements OnInit {
items: Item[]=[];
constructor(private cartservice:CartService) {
}
ngOnInit() {
this.items = this.cartservice.items;
console.log(this.items) //gives empty array
}
}
routing way:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeModule } from './pages/home/home.module';
import { ContactusModule } from './pages/contactus/contactus.module';
import { SingleModule } from './pages/single/single.module';
import { LoginModule } from './pages/login/login.module';
import { SearchpModule } from './pages/searchp/searchp.module';
import { AdminModule } from './pages/admin/admin.module';
import { FindpModule } from './pages/findp/findp.module';
import { AuthGuardService } from './services/auth.service';
import { CartModule } from './pages/cart/cart.module';
const routes: Routes = [
{
path: '',
loadChildren: () => HomeModule,
},
{
path: 'contact',
loadChildren: () => ContactusModule,
},
{
path: 'single/:id',
loadChildren: () => SingleModule,
},
{
path: 'login',
loadChildren: () => LoginModule,
},
{
path: 'searchp/:id',
loadChildren: () => SearchpModule,
},
{
path: 'login/admin',
loadChildren: () => AdminModule, canActivate: [AuthGuardService]
},
{
path: 'cart',
loadChildren: () => CartModule,
},
{
path: 'findp/:str',
loadChildren: () => FindpModule,
},
]
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
cart module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { CartComponent } from './cart.component';
import { CartRoutingModule } from './cart-routing.module';
import { CartService } from 'src/app/services/cart.service';
#NgModule({
declarations: [ CartComponent],
imports: [
CommonModule,
CartRoutingModule,
],
providers:[
]
})
export class CartModule { }
single module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { SingleComponent } from './single.component';
import { SharedModule } from 'src/app/shared/shared.module';
import { SingleRoutingModule } from './single-routing.module';
import { BgviewComponent } from './bgview/bgview.component';
import { HttpService } from 'src/app/services/http.service';
import { CartService } from 'src/app/services/cart.service';
#NgModule({
declarations: [SingleComponent, BgviewComponent],
imports: [
CommonModule,
SharedModule,
SingleRoutingModule,
],
providers:[
HttpService,
]
})
export class SingleModule { }
please help me i'm stuck here.
Also make sure that onAddToCart method is called.
You can simply add some log message inside method to check it.
Make sure that the onAddToCArt method is called.
Related
I writng about create ticket but it happen error.I am stuck in a situation here. I am getting an error like this.
Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Please add a #Pipe/#Directive/#Component annotation.
My add-ticket Component Looks like this
import { Component, OnInit } from '#angular/core';
import { TicketService } from './../../services/ticket.service';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
#Component({
selector: 'app-add-ticket',
templateUrl: './add-ticket.component.html',
styleUrls: ['./add-ticket.component.scss']
})
export class AddTicketComponent implements OnInit {
public ticketForm: FormGroup;
constructor(
public ticketAPI: TicketService,
public fb: FormBuilder
) { }
ngOnInit() {
this.ticketAPI.getTicketsList();
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './pages/login/login.component';
import { RouterModule, Routes } from '#angular/router';
import { HomeComponent } from './pages/home/home.component';
import { SignupComponent } from './pages/signup/signup.component';
import { ProfileComponent } from './pages/profile/profile.component';
import { AddTicketComponent } from './pages/add-ticket/add-ticket.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { environment } from 'src/environments/environment';
import { AuthService } from './services/auth.service';
import { AuthGuard } from './guards/auth.guard';
import { from } from 'rxjs';
import { Component } from '#angular/Core';
// Routes
export const router: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
{ path: 'add-ticket', component: AddTicketComponent}
];
#NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
NavbarComponent,
ProfileComponent,
SignupComponent,
AddTicketComponent,
AppRoutingModule,
],
imports: [
FormsModule,
ReactiveFormsModule,
BrowserModule,
AppRoutingModule,
RouterModule.forRoot(router),
AngularFireAuthModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
],
providers: [AuthService, AngularFireDatabase, AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
Check your routing module is declared with #NgModule looks # is missing.
Check the components too.
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{
path: '',
loadChildren: () => import('./components/home/home.module').then(m => m.HomeModule)
},
{
path: 'home',
loadChildren: () => import('./components/home/home.module').then(m => m.HomeModule)
},
{
path: 'cars',
loadChildren: () => import('./components/cars-list/cars-list.module').then(m => m.CarsListModule)
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
remove AppRoutingModule from declarations
You have a typo in the import in your app.module.ts file
import { Component } from '#angular/Core';
It's lowercase c, not uppercase
import { Component } from '#angular/core';
I am creating an Angular application where I have implemented lazy loading. It is working fine but when ever I am making any HTTP request to the server the action is happening twice.
In my current structure I have created a shared module to store all the common modules and components. I am using ajax service to make all the api calls to backend, AuthTokenService is to store and handle Authentication token-
Feature Module -
import { NgModule, ModuleWithProviders } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import { ReactiveFormsModule, FormsModule } from '#angular/forms';
//Importing HTTP Intercepter and services
import { HTTPInterceptorProvider } from '#/core/_HTTP-interceptor';
import { AjaxService, AuthTokenService } from '#/core/_services';
//Importing pipes
import { SummaryPipe } from '#/core/_pipes';
//Externel Plugins Modules
import { NgSelectModule } from '#ng-select/ng-select';
import { AnimatedNumbersComponent } from '#/modules/shared';
#NgModule({
declarations: [
AnimatedNumbersComponent,
//Pipes used are listed here
SummaryPipe
],
imports: [
CommonModule,
ReactiveFormsModule,
FormsModule,
RouterModule,
NgSelectModule
],
providers: [
],
exports: [
AnimatedNumbersComponent,
ReactiveFormsModule,
FormsModule,
NgSelectModule
]
})
export class FeatureModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [
AjaxService,
AuthTokenService,
HTTPInterceptorProvider
]
};
}
}
App Module -
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations'
import { FeatureModule } from './modules/featured/feature.module'
import { DatePipe } from '#angular/common';
import { NgxSpinnerModule } from "ngx-spinner";
import { AppComponent } from '#/app.component';
#NgModule({
declarations: [
AppComponent,
routingComponents
],
imports: [
HttpClientModule,
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
NgxSpinnerModule, // NGX Spinner
FeatureModule.forRoot()
],
providers: [
DatePipe
],
bootstrap: [AppComponent]
})
export class AppModule { }
App Routing Module -
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AuthGuard, SecureOuterPagesGuard, SecureInnerPagesGuard } from "#/core/_guards";
// Home page of the application
import { IndexComponent } from '#/modules/index/index.component';
import {
LoginComponent,
RegisterComponent,
ForgetPasswordComponent,
ResetPasswordComponent
} from '#/modules/auth';
import {
PageNotFoundComponent,
InternalServerErrorComponent
} from '#/modules/shared';
const routes: Routes = [
{
path: '',
component: IndexComponent
},
{
path: 'login',
component: LoginComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'register',
component: RegisterComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'forget-password',
component: ForgetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'reset-password',
component: ResetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'dashboard',
loadChildren: () => import('./modules/dashboard/dashboard.module').then(m => m.DashboardModule),
canActivate: [AuthGuard]
},
{
path: 'internal-server-error',
component: InternalServerErrorComponent
},
{
path: '**',
component: PageNotFoundComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class AppRoutingModule { }
export const routingComponents = [
IndexComponent,
LoginComponent,
RegisterComponent,
ForgetPasswordComponent,
ResetPasswordComponent,
SessionTimeOutComponent,
PageNotFoundComponent
]
Ajax Service -
import { Injectable } from '#angular/core';
import { environment } from '../../../environments/environment';
import { HttpClient, HttpResponse } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map, timeout } from "rxjs/operators";
#Injectable()
export class AjaxService {
constructor(
private _http: HttpClient,
) { }
apiCall(
data: any,
url: any,
method: 'DELETE' | 'GET' | 'HEAD' | 'POST' | 'JSONP' | 'PUT',
isRawUrlFormat: boolean = false
){
// Checking if the provide url is in raw format or not
if (isRawUrlFormat == false) {
url = environment.API_URL + "/" + url;
}
// creating request variable of type Observable so that any component can subscribe it
let request: Observable<any>;
// setting methods of request type and passing params (url, data, headeers and observe to access complete response)
switch (method) {
case 'GET':
request = this._http.get(url, { observe: 'response' });
break;
case 'POST':
request = this._http.post(url, data, { observe: 'response' });
break;
case 'PUT':
request = this._http.put(url, data, { observe: 'response' });
break;
default:
request = this._http.request(method, url, { observe: 'response' });
}
// returning api result with status, if found any error returns that error
return request.pipe(
timeout(environment.AJAX_TIMEOUT),
map((apiResult : HttpResponse<any>) => {
const status : number = apiResult.status;
let responseObject = apiResult.body;
responseObject.status = status;
// if found status 202 means has a refreshtoken in response then again setting it in localstorage
if (status == 202) {
localStorage.setItem("userToken", apiResult.body.response.data.token);
}
return responseObject;
})
)
}
}
So basically I am trying to create a lazy loaded feature module in my application I have been following the official angular docs - but for some reason its not working.
I have set up my feature module DashboardModule as shown below
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
// MODULES
import { DashboardRoutingModule } from './dashboard-routing.module';
// COMPONENTS
import { DashboardComponent } from './dashboard/dashboard.component';
import { DashboardAlertComponent } from './dashboard-alert/dashboard-alert.component';
import { DashboardSummaryComponent } from './dashboard-summary/dashboard-summary.component';
import { DashboardTasksComponent } from './dashboard-tasks/dashboard-tasks.component';
import { HoldingPageComponent } from './holding-page/holding-page.component';
#NgModule({
imports: [CommonModule, DashboardRoutingModule],
declarations: [
DashboardComponent,
DashboardAlertComponent,
DashboardSummaryComponent,
DashboardTasksComponent,
HoldingPageComponent,
]
})
export class DashboardModule {}
then in my DashboardRoutingModule
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { ActivityComponent } from '../activity-components/activity/activity.component';
import { IsLockedRouteGuard } from '#app/shared/common/auth/is-locked-route-guard';
import { DashboardSummaryComponent } from './dashboard-summary/dashboard-summary.component';
import { SyncComponent } from '#app/popup-components/sync/sync.component';
import { DashboardAlertComponent } from './dashboard-alert/dashboard-alert.component';
import { ChartContainerComponent } from '../chart-components/chart-container/chart-container.component';
import { DashboardTasksComponent } from './dashboard-tasks/dashboard-tasks.component';
#NgModule({
imports: [
RouterModule.forChild([
{ path: 'activity', component: ActivityComponent, canActivate: [IsLockedRouteGuard] },
{ path: 'snapshot', component: DashboardSummaryComponent },
{ path: 'sync', component: SyncComponent },
{
path: 'alerts',
component: DashboardAlertComponent,
canActivate: [IsLockedRouteGuard]
},
{ path: 'charts', component: ChartContainerComponent, canActivate: [IsLockedRouteGuard] },
{ path: 'tasks/:sort', component: DashboardTasksComponent, canActivate: [IsLockedRouteGuard] },
])
],
exports: [RouterModule]
})
export class DashboardRoutingModule {}
so as per the angular docs this has been set up correctly..
now in my AppRoutingModule
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { AppRouteGuard } from './shared/common/auth/auth-route-guard';
#NgModule({
imports: [
RouterModule.forChild([
{
path: 'app',
component: AppComponent,
children: [
{
path: '',
children: [{ path: '', redirectTo: '/dashboard/alerts', pathMatch: 'full' }]
},
{
path: 'main',
canActivate: [AppRouteGuard],
loadChildren: () => import('./main/main.module').then(m => m.MainModule),
data: { preload: true }
},
{
path: 'dashboard',
loadChildren: () => import('./main/dashboard/dashboard.module').then(m => m.DashboardModule)
},
]
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule {}
but whats happening is when I try and go to /dashboard.. I get this error
Component HoldingPageComponent is not part of any NgModule or the module has not been imported into your module.
but I am clearly importing it in the DashboardModule as shown above.. what am I doing wrong??
Thanks
i don't see
RouterModule.forRoot
i think you should use it in AppRoutingModule instead of
RouterModule.forChild
I got this error after ng build and uploading to production server. I'm using angular cli on angular4. All this really started when I added the Route Guard to a feature module. I reverted back to when I had no Guard but the error still persists. When I run ng serve on my local machine I don't get this error.
This is my app module:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { HashLocationStrategy, LocationStrategy } from '#angular/common';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
/* Routing Module */
import { AppRoutingModule } from './app-routing.module';
/* Authentication */
import {AuthenticateService} from './authenticate.service';
import {AuthGuard} from './auth.guard';
import {DashboardModule} from './dashboard/dashboard.module';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
DashboardModule,
AppRoutingModule
],
providers: [
{ provide: LocationStrategy, useClass: HashLocationStrategy},
AuthenticateService,
AuthGuard
],
bootstrap: [AppComponent]
})
export class AppModule { }
My auth Service:
import { Injectable } from '#angular/core';
import {Response, Headers, Http, RequestOptionsArgs} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class AuthenticateService {
baseUrl = 'myurl/public';
constructor(private http: Http) { }
register(form) {
return this.http.post(`${this.baseUrl}/register`, form)
.map((response: Response) => {
const user = response.json();
if (user.status) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('loggedUser', JSON.stringify(user));
}
return user;
})
.catch((error: any) => Observable.throw(error.json().error || {message: 'Server Error'}));
}
login(form): Observable<Response> {
const headersObj = new Headers();
headersObj.set('Content-Type', 'application/json');
const requestArg: RequestOptionsArgs = { headers: headersObj, method: 'POST' };
// const telephone = form.telephone;
// const password = form.password;
return this.http.post(`${this.baseUrl}/login`, form, requestArg)
.map((response: Response) => {
const user = response.json();
if (user.response.status) {
localStorage.setItem('loggedUser', JSON.stringify(user.response));
}
return user.response;
})
.catch((error: any) => Observable.throw(error.json().error || {message: 'Server Error'}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('loggedUser');
}
}
My Route Guard:
import { Injectable } from '#angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
// import {AuthenticateService} from './authenticate.service';
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if ((!localStorage.getItem('loggedUser'))) {
// not logged in so redirect to login page
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
} else {
return true;
}
}
}
App routing Module:
import { NgModule } from '#angular/core';
import {RouterModule, Routes} from '#angular/router';
import {LoginComponent} from './login/login.component';
import {RegisterComponent} from './register/register.component';
export const routes: Routes = [
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
];
#NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
Guarded Module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import {FormsModule} from '#angular/forms';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { DashboardComponent } from './dashboard.component';
import { DashboardHomeComponent } from './dashboard-home/dashboard-home.component';
import { UsersComponent } from './users/users.component';
import { TransactionsComponent } from './transactions/transactions.component';
import { UsersService } from './services/users.service';
#NgModule({
imports: [
CommonModule,
FormsModule,
RouterModule,
DashboardRoutingModule
],
exports: [ DashboardComponent ],
declarations: [ DashboardComponent, DashboardHomeComponent, UsersComponent, TransactionsComponent],
providers: [ UsersService ]
})
export class DashboardModule { }
Feature Module Component:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import {DashboardComponent} from './dashboard.component';
import {DashboardHomeComponent} from './dashboard-home/dashboard-home.component';
import {UsersComponent} from './users/users.component';
import {TransactionsComponent} from './transactions/transactions.component';
import {AuthGuard} from '../auth.guard';
export const dashboardRoutes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [ AuthGuard ],
children: [
{path: '', component: DashboardHomeComponent},
{path: 'users', component: UsersComponent},
{path: 'transactions', component: TransactionsComponent}
]}
// {path: 'dashboard', component: DashboardComponent}
];
#NgModule({
imports: [
RouterModule.forChild(dashboardRoutes)
],
exports: [
RouterModule
],
declarations: []
})
export class DashboardRoutingModule { }
I found the error, I imported Router module in my feature module and also in my feature-routing module.
I'm having an issue with my Angular2/Meteor application.
I'm trying to redirect to a component from an other but it doesn't seem to load the first time. However, when I refresh the page, it loads perfectly.
When I debug, I see my html view without any of the variables displaying, my variables have values that seems correct, but they doesn't show on the View.
This is my Guard:
import { CanActivate } from "#angular/router";
import { Meteor } from 'meteor/meteor';
import { Router } from '#angular/router';
import { Injectable } from '#angular/core';
#Injectable()
export class RouteGuardService implements CanActivate {
constructor(public router: Router) { }
canActivate() {
if (Meteor.userId() != undefined) {
return true;
}
else {
let link = ['accueil'];
this.router.navigate(link);
return false;
}
}
}
My route.module :
import { Route } from '#angular/router';
import {AccueilComponent} from "./pages/accueil/accueil.component";
import {ChannelsComponent} from "./pages/channel/channels.component";
import { RouteGuardService } from './services/routeGuard.service';
export const routes: Route[] = [
{ path: '', component: AccueilComponent },
{ path: 'accueil', component: AccueilComponent, pathMatch: 'full' },
{ path: 'channel', component: ChannelsComponent, canActivate: [RouteGuardService], pathMatch: 'full'},
];
I hope I was clear with my explanation. Do not hesitate to ask more information.
Thanks !
EDIT:
My app.module:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { Ng2DragDropModule } from 'ng2-drag-drop';
import { AccountsModule } from 'angular2-meteor-accounts-ui';
import { AppComponent } from './app.component';
import { MomentModule } from "angular2-moment";
import { ModalModule } from 'ngx-modialog';
import { BootstrapModalModule } from 'ngx-modialog/plugins/bootstrap';
import { ChannelModal } from './pages/channel/channel_search/channel-list.modal';
import { RouteGuardService } from './services/routeGuard.service';
import { AccueilComponent } from "./pages/accueil/accueil.component";
import { LOGIN_DECLARATIONS } from './pages/login';
import { CHANNEL_DECLARATIONS } from './pages/channel';
import { routes } from './app.routes';
#NgModule({
imports: [
RouterModule.forRoot(routes),
Ng2DragDropModule.forRoot(),
ModalModule.forRoot(),
BrowserModule,
AccountsModule,
FormsModule,
ReactiveFormsModule,
MomentModule,
BootstrapModalModule,
],
declarations: [
AppComponent,
AccueilComponent,
...LOGIN_DECLARATIONS,
...CHANNEL_DECLARATIONS,
ChannelModal
],
bootstrap: [
AppComponent
],
entryComponents: [
ChannelModal
],
providers:[
RouteGuardService
]
})
export class AppModule { }
Alright I found an answer. I don't know if it's the best solution, but at least it's working.
this.zone.run(() => this.router.navigate(['channel']));
This solve my problem.