ngx-cookie - blank cookie object in server side rendering - javascript

I have a angular application in which angular universal is enabled and i am rendering data from API but that includes the work of cookies. I make API call after checking a value in user browser cookies.
But for Angular SSR(server side rendering) there is no cookie and i am getting {} blank object when trying to use this console.log(this.cookie.getAll());.
I am using ngx-cookie package and my installation is this
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { SlickCarouselModule } from 'ngx-slick-carousel';
import { SharedModule } from './shared/shared.module';
import { CookieModule } from 'ngx-cookie';
import { HttpClientModule } from '#angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CommonModule } from '#angular/common';
import { TransferHttpCacheModule } from '#nguniversal/common';
import { NgtUniversalModule } from '#ng-toolkit/universal';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }),
CookieModule.forRoot(),
AppRoutingModule,
HttpClientModule,
CommonModule,
TransferHttpCacheModule,
NgtUniversalModule,
SlickCarouselModule,
SharedModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.server.module.ts
import { NgModule } from '#angular/core';
import { ServerModule, ServerTransferStateModule } from '#angular/platform-server';
import { CookieService, CookieBackendService } from 'ngx-cookie';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { ModuleMapLoaderModule } from '#nguniversal/module-map-ngfactory-loader';
import { SharedModule } from './shared/shared.module';
#NgModule({
imports: [
AppModule,
ServerModule,
ModuleMapLoaderModule,
ServerTransferStateModule,
SharedModule
],
bootstrap: [AppComponent],
providers: [{ provide: CookieService, useClass: CookieBackendService }]
})
export class AppServerModule {}
server.ts
I have applied this
app.get('*', (req, res) => {
res.render('index', {
req: req,
res: res,
providers: [
{
provide: 'REQUEST', useValue: (req)
},
{
provide: 'RESPONSE', useValue: (res)
}
]
});
});
Still i can only access cookies in browser but not server side.
Any help would be appreciated.

You can send cookies with every request to server using Interceptor
Here is an example how to use it:
intercreptor.service.ts
import { Injectable } from '#angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '#angular/common/http';
import { Observable } from 'rxjs';
import { CookieService } from 'ngx-cookie';
#Injectable()
export class InterceptorService implements HttpInterceptor {
constructor(private cookies: CookieService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = this.cookies.get("my-access-token");
if(token) req = req.clone({
setHeaders: { Authorization: `Bearer ${token}`}
});
return next.handle(req)
}
}
intercreptor.module.ts
import { NgModule } from '#angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { InterceptorService } from './interceptors/authorization';
#NgModule({
imports: [
HttpClientModule
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorService,
multi: true
}]
})
export class InterceptorModule { }
and import InterceptorModule into your app.module.ts

Related

Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Please add a #Pipe/#Directive/#Component annotation

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

NG002 Error: Could not be resolved to an NgModule class

I have added a new component to my angular project and made sure it is imported in my app module however I get a NG002 error saying:
error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.
Is it missing an #NgModule annotation?
export class NavigationBarDriverComponent {
My app module looks like this:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import {GoogleMapsAPIWrapper} from '#agm/core';
import { AppComponent } from './app.component';
import { ButtonComponent } from './button/button.component';
import { AgmCoreModule } from '#agm/core';
import { AgmDirectionModule } from 'agm-direction';
import { GooglePlaceModule } from "ngx-google-places-autocomplete";
import { NavigationBarComponent } from './navigation-bar/navigation-bar.component';
import { NavigationBarDriverComponent} from './navigation-bar-driver/navigation-bar-driver.component';
import { LayoutModule } from '#angular/cdk/layout';
import { MatToolbarModule } from '#angular/material/toolbar';
import { MatButtonModule } from '#angular/material/button';
import { MatSidenavModule } from '#angular/material/sidenav';
import { MatIconModule } from '#angular/material/icon';
import { MatListModule } from '#angular/material/list';
import { NoopAnimationsModule } from '#angular/platform-browser/animations';
import { OwlDateTimeModule, OwlNativeDateTimeModule } from 'ng-pick-datetime';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { MatDialogModule } from '#angular/material/dialog';
import { RouteDialogComponent } from './route-dialog/route-dialog.component';
import { AppRoutingModule, routingComponents } from './app-routing.module';
#NgModule({
declarations: [
AppComponent,
ButtonComponent,
NavigationBarComponent,
NavigationBarDriverComponent,
RouteDialogComponent,
routingComponents
],
imports: [
BrowserModule,
AgmCoreModule.forRoot({
apiKey: 'AIzaSyDnibzvTPaquvcrp9ZYZZ5EFgzncyK1jys'
}),
AgmDirectionModule,
GooglePlaceModule,
LayoutModule,
MatToolbarModule,
MatButtonModule,
MatSidenavModule,
MatIconModule,
MatListModule,
NoopAnimationsModule,
HttpClientModule,
OwlDateTimeModule,
OwlNativeDateTimeModule,
BrowserAnimationsModule,
MatDialogModule,
MatButtonModule,
AppRoutingModule,
NavigationBarDriverComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
and my NavigationBarDriverComponent looks like this:
import { Component, NgModule } from '#angular/core';
import { BreakpointObserver, Breakpoints } from '#angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
#Component({
selector: 'app-navigation-bar-driver',
templateUrl: './navigation-bar-driver.component.html',
styleUrls: ['./navigation-bar-driver.component.css']
})
export class NavigationBarDriverComponent {
drawer;
isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches),
shareReplay()
);
constructor(private breakpointObserver: BreakpointObserver) {}
}
I tried to restart the angular server with both "ng serve" and also "ng serve --prod" as I saw it suggested in another thread.
Remove NavigationBarDriverComponent from your app module import.

Uncaught TypeError: Cannot read property 'prototype' of undefined at __extends (Subscriber.js:5)

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.

AppComponent.html:1 ERROR Error: No provider for Http! at injectionError (core.es5.js:1169)

When viewing the console log, I am getting this error 'No provider for Http!
at injectionError', in my Angular 4 application when trying to use the Http module. My app.module.ts file is
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import { DataService } from './services/data.service';
#NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
And my service file, 'data.service.ts' is
import { Injectable } from '#angular/core';
import { Http } from '#angular/Http';
import 'rxjs/add/operator/map';
#Injectable()
export class DataService {
constructor(public http: Http) {
console.log('Data service connected...');
}
getPosts() {
return this.http.get('https//jsonplaceholder.typicode.com/posts')
.map(res => res.json());
}
}
As shown, I have included the HttpModule in the app.module.ts file. What else I'm I missing?
It seems like you had typo in data.service.ts's import Http statement from path,
Instead of
import { Http } from '#angular/Http';
it should be
import { Http } from '#angular/http';

How to embed twitter timeline to Angular4 app

New to Angular, please bear with me. I need to load in tweets from a specific timeline. What is the best way to accomplish this? I've tried using this package (https://www.npmjs.com/package/ng4-twitter-timeline), and have followed the instructions in that documentation, but I still get the error that "ng4-twitter-timeline is not a known element."
I've also tried adding in
<script src="https://platform.twitter.com/widgets.js" async></script>
to index.html...
Are there additional scripts that need to be loaded in for this to work?
app.module.ts
...
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { RouterModule } from '#angular/router';
import { SwiperModule } from 'angular2-useful-swiper';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { ShareModule } from 'ng2share/share.module';
import { MasonryModule } from 'angular2-masonry';
import { routes } from './app-routing.module';
import { Ng4TwitterTimelineModule } from 'ng4-twitter-timeline/lib/index';
#NgModule({
declarations: [
...
],
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
AngularFontAwesomeModule,
SwiperModule,
RouterModule.forRoot(routes),
ShareModule,
MasonryModule,
Ng4TwitterTimelineModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
tweets.component.ts
import { Component, OnInit } from '#angular/core';
import { Ng4TwitterTimelineService } from 'ng4-twitter-timeline/lib/index';
#Component({
selector: 'app-tweets',
templateUrl: './tweets.component.html',
styleUrls: ['./tweets.component.scss']
})
export class TweetsComponent implements OnInit {
constructor(private ng4TwitterTimelineService: Ng4TwitterTimelineService) {}
ngOnInit() {}
}
tweets.component.html
<ng4-twitter-timeline [dataSrc]="{sourceType: 'profile',screenName: 'lokers_one'}" [opts]="{tweetLimit: 2}"></ng4-twitter-timeline>
You should add .forRoot when you imports Ng4TwitterTimelineModule in #ngModule. So your app.module.ts should look like that:
...
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { RouterModule } from '#angular/router';
import { SwiperModule } from 'angular2-useful-swiper';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { ShareModule } from 'ng2share/share.module';
import { MasonryModule } from 'angular2-masonry';
import { routes } from './app-routing.module';
import { Ng4TwitterTimelineModule } from 'ng4-twitter-timeline/lib/index';
#NgModule({
declarations: [
...
],
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
AngularFontAwesomeModule,
SwiperModule,
RouterModule.forRoot(routes),
ShareModule,
MasonryModule,
Ng4TwitterTimelineModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Figured it out, everyone. The account used in the demo has protected tweets... which is why nothing was embedding... I changed the account and it does work. But still don't understand why I'm still getting this error: 'ng4-twitter-timeline' is not a known element'

Categories