Angular 6 + Routes Resolver = 404 page in production - javascript

I am new to Angular Community coming from rails ; I am working on a site where I can post case studies of my clients website. So far I am loving angular but I am running into an issue that worries me a bit. The issue that I cant seem to use hyperlinks to reference any of the projects. For example if you click on this the application will return a 404 status but if you start from the root page everything will run no problem.
Solutions I have tried
Adding a resolver to the route to fetch the data before loading the
page; it works but still no hyperlink.
Can anyone help me figure out what I am missing or doing wrong;
Below is my code; Any help would be appreciated
Project.service.ts
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable, of } from 'rxjs';
import { map, } from 'rxjs/operators';
import { Injectable } from '#angular/core';
import { Project } from '../../models/project';
import { HttpClient } from '#angular/common/http';
import { Post } from '../post';
#Injectable()
export class ProjectService {
ProjectListRef: Observable<any[]>;
featuredProjectList: Observable<any[]>;
posts: Array<Post>;
constructor( private database: AngularFirestore, private http: HttpClient) {
// Link For All Projects Page
const allProjectsListLink = this.database.collection<Project>('projects', ref => ref.orderBy('company_name'));
// Link For Featured Project Page
const featuredProjectsListLink = this.database.collection<Project>('projects', ref => ref.limit(5));
this.ProjectListRef = allProjectsListLink.snapshotChanges()
// using map pipe
.pipe(map( actions => {
return actions.map(a => {
// Get Document Data
const data = a.payload.doc.data() as Project;
// Get Document Id
const id = a.payload.doc.id;
return {id, ...data};
});
}));
this.featuredProjectList = featuredProjectsListLink.snapshotChanges()
// using map pipe
.pipe(map( actions => {
return actions.map(a => {
// Get Document Data
const data = a.payload.doc.data() as Project;
// Get Document Id
const id = a.payload.doc.id;
return {id, ...data};
});
}));
}
getAllProjects() {
return this.ProjectListRef;
}
getFeaturedProjects() {
return this.featuredProjectList;
}
getProject(id: string) {
console.log(id);
return this.database.collection('projects').doc(id)
.ref.get().then( doc => doc.data() );
}
}
Project.component.ts
import { Component, OnInit, Injectable, Inject } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { tap } from 'rxjs/operators';
import { ProjectService } from '../../app/services/project.service';
import { AngularFirestore } from 'angularfire2/firestore';
import { Project } from '../../models/project';
import { DOCUMENT } from '#angular/common';
#Injectable()
#Component({
selector: 'app-project-page',
templateUrl: './project-page.component.html',
styleUrls: ['./project-page.component.scss']
})
export class ProjectPageComponent implements OnInit {
project: Project;
projectId: any;
projectRef: any;
constructor(#Inject(DOCUMENT) private document: any, private router: Router,
private route: ActivatedRoute,
public database: AngularFirestore,
private projectService: ProjectService
) {
}
ngOnInit() {
// print out the data from the route resolver
this.route.data.pipe(
tap(console.log))
.subscribe(
data => this.project = data['project']
);
}
goToWebsite(url) {
this.document.location.href = url;
}
}
3. **ProjectResolver.ts**
import { ProjectService } from './../../app/services/project.service';
import { Project } from './../project';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { Observable } from 'rxjs';
import { Injectable } from '#angular/core';
#Injectable()
export class ProjectResolver implements Resolve<Project> {
constructor(private projectService: ProjectService) {
}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<Project>|Promise<any> {
return this.projectService.getProject(route.params['id']);
}
}
Application Routes
import { AddLeadPageComponent } from './add-lead-page/add-lead-page.component';
import { GoogleAdsPageComponent } from './google-ads-page/google-ads-page.component';
import { WebAppsPageComponent } from './web-apps-page/web-apps-page.component';
import { BrandedWebsitesPageComponent } from './branded-websites-page/branded-websites-page.component';
import { ServiceOverviewPageComponent } from './service-overview-page/service-overview-page.component';
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomePageComponent } from './home-page/home-page.component';
import { AboutPageComponent } from './about-page/about-page.component';
import { BlogPageComponent } from './blog-page/blog-page.component';
import { WebServicesPageComponent } from './web-services-page/web-services-page.component';
import { SEMPageComponent } from './sempage/sempage.component';
import { ContactPageComponent } from './contact-page/contact-page.component';
import { AllProjectsPageComponent } from './all-projects-page/all-projects-page.component';
import { ResearchServicePageComponent } from './research-service-page/research-service-page.component';
import { ProjectPageComponent } from './project-page/project-page.component';
import { TeamPageComponent } from './team-page/team-page.component';
import { NewProjectComponent } from './new-project/new-project.component';
import { DigitalMarketingPageComponent } from './digital-marketing-page/digital-marketing-page.component';
import { ProjectResolver } from '../models/resolvers/project.resolver';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomePageComponent},
{ path: 'about', component: AboutPageComponent},
{ path: 'blog', component: BlogPageComponent},
{ path: 'team', component: TeamPageComponent},
{ path: 'portfolio', component: AllProjectsPageComponent},
{ path: 'services', component: ServiceOverviewPageComponent},
{ path: 'project/:id', component: ProjectPageComponent, resolve: { project: ProjectResolver}},
{ path: 'brand-strategy', component: ResearchServicePageComponent},
{ path: 'digital-strategy', component: DigitalMarketingPageComponent},
{ path: 'custom-websites', component: BrandedWebsitesPageComponent},
{ path: 'web-apps', component: WebAppsPageComponent},
{ path: 'google-ads', component: GoogleAdsPageComponent},
{ path: 'web-design-development', component: WebServicesPageComponent},
{ path: 'search-engine-marketing', component: SEMPageComponent},
{ path: 'start-new-project', component: ContactPageComponent},
{ path: 'new-project', component: NewProjectComponent},
// post trial
{ path: 'posts/add', component: AddLeadPageComponent},
{ path: 'posts/add/:id', component: AddLeadPageComponent},
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled'})
],
exports: [RouterModule]
})
export class AppRoutingModule { }

You don't have any error in your angular code. The problem you are facing is that the urls are not being rewritten to index.html. You need to configure this in your Firebase settings(firebase.json). This is the easiest and most common configuration:
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}

Related

route navigation is not working in angular 9

I am working on a login and home component in my angular app.
Login service is validating the username and password of the user.
After successful login, it should redirect user to the home page.
But router redirect is not working properly.
login component
import { Router } from '#angular/router';
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { User } from 'src/app/shared/models/user';
import { AuthService } from '../services/auth.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
userName: FormControl;
password: FormControl;
loginFormGroup: FormGroup;
loginError: boolean;
errorMessage: string;
messageString: string;
constructor(private router: Router, private authService: AuthService) { }
ngOnInit() {
this.userName = new FormControl("", [Validators.required]);
this.password = new FormControl("", [Validators.required]);
this.loginFormGroup = new FormGroup({
userName: this.userName,
password: this.password
});
}
login() {
this.loginError = false;
if (this.loginFormGroup.valid) {
let user: User = new User();
user.userId = this.userName.value;
user.password = this.password.value;
this.authService.login(user)
.subscribe(res =>
{
console.log(res)
this.router.navigate(["home"])
console.log("res")
},
error =>
{
console.log(error)
});
}
}
}
and login service
import { Injectable } from "#angular/core";
import { Router } from "#angular/router";
import { Observable } from "rxjs";
import { share } from "rxjs/operators";
import { environment} from 'src/environments/environment';
import { HttpClient, HttpParams, HttpHeaders} from "#angular/common/http";
import { User } from 'src/app/shared/models/user';
#Injectable({ providedIn: "root" })
export class AuthService {
user: User;
resp=401;
get userDetail(): User {
return this.user;
}
constructor(
private router: Router,
private http: HttpClient
) {
}
login(user: User): Observable<any> {
var formData = new FormData();
formData.append("userId", user.userId);
formData.append("password", user.password);
return this.http.get<any>(url+"Validate_Login_User",{
headers: new HttpHeaders(),
params: new HttpParams().set("User_Id","user.userId")
})
}
}
routes
import { NgModule } from "#angular/core";
import { Routes, RouterModule } from "#angular/router";
import { AuthGuard } from "./authentication/services/auth.guard";
import { LoginComponent } from "./authentication/login/login.component";
import { LayoutComponent } from "./shared/components/layout/layout.component";
import { PageNotFoundComponent } from "./shared/components/page.not.found.component";
import { MenuComponent } from './menu/menu.component';
const routes: Routes = [
{ path: "login", component: LoginComponent },
{
path: "home",
component: HomeComponent,
canActivate: [AuthGuard],
children: [
{
//childroutes
},
{
//childroutes
},
],
},
{ path: "**", component: PageNotFoundComponent },
{ path: "Menu", component: MenuComponent}
];
#NgModule({
imports: [
RouterModule.forRoot(routes, {
onSameUrlNavigation: "ignore",
useHash: true,
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
console log in login component
even though the console is printing success, route navigate is not happening and its still in login page
replace your code with the following piece of code, that should work.
this.loginError = false;
if (this.loginFormGroup.valid) {
let user: User = new User();
user.userId = this.userName.value;
user.password = this.password.value;
this.authService.login(user)
.subscribe(res =>
{
console.log(res)
this.router.navigate(["/home"])
console.log("res")
},
error =>
{
console.log(error)
});
}
}
Edited:
Please replace your ngModule with the below code:
#NgModule({
imports: [
RouterModule.forRoot(routes, {
useHash: true,
}),
],
exports: [RouterModule],
})
Try this.
this.router.navigateByUrl('/home');

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 6 Dynamic Routing Table From Database

I want to define the routing table in app.routing.ts from the database. The data for the routing file will be retrieved from the table in the database on the initialization of the project.
I have tried the same by making an HTTP Get call from app.component.ts and adding the routes from the same file into routes configure.
It doesn't give the error when I add the route after making the database call and adding the same. When I route the same, It gives the me an error that no routes are available.
Please help me out the same. Any kind of help is appreciated
I have tried to develop the prototype for the same.
app.component.ts
import { Component } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
import { Routes } from '#angular/router';
import { Router } from '#angular/router';
import { AppModule } from './app.module';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
routes: Routes = [];
data: any;
loaded: boolean = false;
constructor(private http: HttpClient, private router: Router) {
this.getJSON().subscribe(data => {
//routes.push(data);
if (!this.loaded) {
let routerConfig = this.router.config;
//routerConfig.unshift(data[0]);
// routerConfig[0]._loadedConfig.routes[0].children.unshift({
// path: `lazy`,
// loadChildren: 'app/lazy.module#LazyModule'
// });
// console.log('/lazy route (Portal child) added',
routerConfig);
//this.router.resetConfig(routerConfig);
let compName = data[0].component;
let comp: any =
(<any>AppModule).__annotations__[0].declarations.find(comp =>
{
return comp.name === compName;
});
routerConfig.unshift({path: 'login', component:
mapping[comp]})
this.router.resetConfig(routerConfig);
this.loaded = true;
}
});
}
public getJSON(): Observable<any> {
return this.http.get("https://api.myjson.com/bins/1g16wr");
}
}
//app.routing.ts
import { RouterModule, Routes } from '#angular/router';
import { LoginComponent } from "./login/login.component";
import { AddUserComponent } from "./add-user/add-user.component";
import { ListUserComponent } from "./list-user/list-user.component";
import { EditUserComponent } from "./edit-user/edit-user.component";
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
const routes: Routes = [];
// function f(){
// console.log(this.http.get("https://api.myjson.com/bins/mfh63"));
// }
// f();
// const routes: Routes = [
// { path: 'login', component: LoginComponent },
// { path: 'add-user', component: AddUserComponent },
// { path: 'list-user', component: ListUserComponent },
// { path: 'edit-user', component: EditUserComponent },
// { path: '*', component: LoginComponent }
// ];
// { path: 'login', component: LoginComponent },
// { path: 'add-user', component: AddUserComponent },
// { path: 'list-user', component: ListUserComponent },
// { path: 'edit-user', component: EditUserComponent },
// { path: '*', component: LoginComponent }
// ];
// export class TestComponent implements OnInit {
// constructor(private http: HttpClient) {
// console.log('second');
// this.getJSON().subscribe(data => {
// let testData = data;
// routes.push(testData);
// console.log(routes);
// });
// }
// ngOnInit() {
// console.log('first');
// }
// public getJSON(): Observable<any> {
// return this.http.get("https://api.myjson.com/bins/mfh63");
// }
// }
export const routing = RouterModule.forRoot(routes);
app.component.html
<router-outlet></router-outlet>
app.module.ts
import { RouterModule, Routes } from '#angular/router';
import { LoginComponent } from "./login/login.component";
import { AddUserComponent } from "./add-user/add-user.component";
import { ListUserComponent } from "./list-user/list-user.component";
import { EditUserComponent } from "./edit-user/edit-user.component";
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
const routes: Routes = [];
// function f(){
// console.log(this.http.get("https://api.myjson.com/bins/mfh63"));
// }
// f();
// const routes: Routes = [
// { path: 'login', component: LoginComponent },
// { path: 'add-user', component: AddUserComponent },
// { path: 'list-user', component: ListUserComponent },
// { path: 'edit-user', component: EditUserComponent },
// { path: '*', component: LoginComponent }
// ];
// { path: 'login', component: LoginComponent },
// { path: 'add-user', component: AddUserComponent },
// { path: 'list-user', component: ListUserComponent },
// { path: 'edit-user', component: EditUserComponent },
// { path: '*', component: LoginComponent }
// ];
// export class TestComponent implements OnInit {
// constructor(private http: HttpClient) {
// console.log('second');
// this.getJSON().subscribe(data => {
// let testData = data;
// routes.push(testData);
// console.log(routes);
// });
// }
// ngOnInit() {
// console.log('first');
// }
// public getJSON(): Observable<any> {
// return this.http.get("https://api.myjson.com/bins/mfh63");
// }
// }
export const routing = RouterModule.forRoot(routes);
it shows that the specific route is not found. If anything specific is needed, please reply I will upload you the project.

Can't display a component in AngularJS

I am building a small cinema website. My issue is that I have a list, when you click the listen a button is displayed with a function, when you click that function it should give you more details on the item you have clicked. I have tried to work through the Angular Tour of Heroes again but I can't get the details to show up.
https://i.imgur.com/mzUcalv.png
The above is what is seen, some details should be shown on the page but there is no error relevant to why it is not showing.
`import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroesComponent } from './heroes.component';
import { HeroService } from './hero.service';
import { AccordionModule } from 'primeng/primeng';
import { AppRoutingModule } from './app-routing.module';
import { RatingModule} from 'primeng/primeng';
import { GalleriaModule } from 'primeng/primeng';
import { CinemaComponent} from './cinema.component';
import { ContactComponent } from './contact.component';
import { AgmCoreModule } from 'angular2-google-maps/core';
import { ReviewsComponent } from './reviews.component';
import { TabViewModule } from 'primeng/primeng';
import { CinemaService } from './cinema.service';
import { CinemaDetailComponent } from './cinema-detail.component';
#NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
AccordionModule,
RatingModule,
GalleriaModule,
TabViewModule,
AgmCoreModule.forRoot({
apiKey: 'AIzaSyDmQWd7DM4PcMvkzp_uopvIkbyjPMWzHeM'
})
],
declarations: [
AppComponent,
DashboardComponent,
HeroDetailComponent,
HeroesComponent,
CinemaComponent,
ContactComponent,
ReviewsComponent,
CinemaDetailComponent
],
providers: [ HeroService, CinemaService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
`
App Module
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
import { CinemaComponent } from './cinema.component';
import { ContactComponent } from './contact.component';
import { ReviewsComponent } from './reviews.component';
import { CinemaDetailComponent } from './cinema-detail.component';
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent },
{ path: 'cinema', component: CinemaComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'reviews', component: ReviewsComponent },
{ path: 'detail/:id', component: CinemaDetailComponent}
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
Cinema Detail Component
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute, Params } from '#angular/router';
import { Location } from '#angular/common';
import { Cinema } from './cinema';
import { CinemaService } from './cinema.service';
#Component({
moduleId: module.id,
selector: 'my-cinema-detail',
templateUrl: 'cinema-detail.component.html',
styleUrls: [ 'cinema-detail.component.css' ]
})
export class CinemaDetailComponent implements OnInit {
cinema: Cinema;
constructor(
private cinemaService: CinemaService,
private route: ActivatedRoute,
private location: Location
) {}
ngOnInit(): void {
this.route.params.forEach((params: Params) => {
let id = +params['id'];
this.cinemaService.getCinema(id)
.then(Cinema => this.cinema = Cinema);
});
}
goBack(): void {
this.location.back();
}
}
The HTML that should be displayed
<
div *ngIf="cinema">
<h2>{{cinema.name}} details!</h2>
<div>
<label>id: </label>{{cinema.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="cinema.name" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
My cinema.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { CinemaDetailComponent } from './cinema-detail.component';
import { Cinema } from './cinema';
import { CinemaService } from './cinema.service';
#Component({
moduleId: module.id,
selector: 'my-cinema',
templateUrl: 'cinema.component.html',
styleUrls: [ 'cinema.component.css' ]
})
export class CinemaComponent implements OnInit {
cinemas: Cinema[];
selectedCinema: Cinema;
constructor(
private router: Router,
private cinemaService: CinemaService) { }
getCinemas(): void {
this.cinemaService.getCinemas().then(cinemas => this.cinemas = cinemas);
}
ngOnInit(): void {
this.getCinemas();
}
onSelect(cinema: Cinema): void {
this.selectedCinema = cinema;
}
gotoDetail(): void {
this.router.navigate(['/detail', this.selectedCinema.id]);
}
}
cinema.service.ts file
import { Cinema } from './cinema';
import { CINEMAS } from './mock-cinema';
import { Injectable } from '#angular/core';
#Injectable()
export class CinemaService {
getCinemas(): Promise<Cinema[]> {
return Promise.resolve(CINEMAS);
}
getHeroesSlowly(): Promise<Cinema[]> {
return new Promise<Cinema[]>(resolve =>
setTimeout(resolve, 2000)) // delay 2 seconds
.then(() => this.getCinemas());
}
getCinema(id: number): Promise<Cinema> {
return this.getCinemas()
.then(cinemas => cinemas.find(cinema => cinema.id === id));
}
}
Can anybody help figure out why it isn't displayed? I haven't posted the export class for Cinema which just contains an id:number and name:string or the array which is correct (as it displays the list to click on). Thanks for reading.

Angular 2: Passing Data to Routes?

I am working on this angular2 project in which I am using ROUTER_DIRECTIVES to navigate from one component to other.
There are 2 components. i.e. PagesComponent & DesignerComponent.
I want to navigate from PagesComponent to DesignerComponent.
So far its routing correctly but I needed to pass page Object so designer can load that page object in itself.
I tried using RouteParams But its getting page object undefined.
below is my code:
pages.component.ts
import {Component, OnInit ,Input} from 'angular2/core';
import { GlobalObjectsService} from './../../shared/services/global/global.objects.service';
import { ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';
import { DesignerComponent } from './../../designer/designer.component';
import {RouteParams} from 'angular2/router';
#Component({
selector: 'pages',
directives:[ROUTER_DIRECTIVES,],
templateUrl: 'app/project-manager/pages/pages.component.html'
})
#RouteConfig([
{ path: '/',name: 'Designer',component: DesignerComponent }
])
export class PagesComponent implements OnInit {
#Input() pages:any;
public selectedWorkspace:any;
constructor(private globalObjectsService:GlobalObjectsService) {
this.selectedWorkspace=this.globalObjectsService.selectedWorkspace;
}
ngOnInit() { }
}
In the html, I am doing following:
<scrollable height="300" class="list-group" style="overflow-y: auto; width: auto; height: 200px;" *ngFor="#page of pages">
{{page.name}}<a [routerLink]="['Designer',{page: page}]" title="Page Designer"><i class="fa fa-edit"></i></a>
</scrollable>
In the DesignerComponent constructor I have done the following:
constructor(params: RouteParams) {
this.page = params.get('page');
console.log(this.page);//undefined
}
So far its routing correctly to designer, but when I am trying to access page Object in designer then its showing undefined.
Any solutions?
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data but the new (RC.1) router doesn't yet.
Update
data was re-introduced in RC.4 How do I pass data in Angular 2 components while using Routing?
It changes in angular 2.1.0
In something.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '#angular/router';
import { MaterialModule } from '#angular/material';
import { FormsModule } from '#angular/forms';
const routes = [
{
path: '',
component: BlogComponent
},
{
path: 'add',
component: AddComponent
},
{
path: 'edit/:id',
component: EditComponent,
data: {
type: 'edit'
}
}
];
#NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes),
MaterialModule.forRoot(),
FormsModule
],
declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }
To get the data or params in edit component
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute, Params, Data } from '#angular/router';
#Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.route.snapshot.params['id'];
this.route.snapshot.data['type'];
}
}
You can do this:
app-routing-modules.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { PowerBoosterComponent } from './component/power-booster.component';
export const routes: Routes = [
{ path: 'pipeexamples',component: PowerBoosterComponent,
data:{ name:'shubham' } },
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:
power-booster-component.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute, Params, Data } from '#angular/router';
#Component({
selector: 'power-booster',
template: `
<h2>Power Booster</h2>`
})
export class PowerBoosterComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
//this.route.snapshot.data['name']
console.log("Data via params: ",this.route.snapshot.data['name']);
}
}
So you can get the data by this.route.snapshot.data['name'].
1. Set up your routes to accept data
{
path: 'some-route',
loadChildren:
() => import(
'./some-component/some-component.module'
).then(
m => m.SomeComponentModule
),
data: {
key: 'value',
...
},
}
2. Navigate to route:
From HTML:
<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>
Or from Typescript:
import {Router} from '#angular/router';
...
this.router.navigate(
[
'/some-component',
{
key: 'value',
...
}
]
);
3. Get data from route
import {ActivatedRoute} from '#angular/router';
...
this.value = this.route.snapshot.params['key'];

Categories

Resources