Angular auth.guard no persisten auth - javascript

Authentication doesn't seem to persist after page has been refreshed. Whenever I login, it successfully redirects me. but, when i refreshed, accessing is not possible anymore.
here is the auth guard
router
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavComponent } from './components/nav/nav.component';
import { HomeComponent } from './components/home/home.component';
import { GalleryComponent } from './components/gallery/gallery.component';
import { FooterComponent } from './components/footer/footer.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { FIREBASECONFIG as firebaseConfig } from './config/firebase-config';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { ScrollToModule } from 'ng2-scroll-to';
import { NgxCarouselModule } from 'ngx-carousel';
import { AnimateOnScrollModule } from 'ng2-animate-on-scroll';
import { AuthService } from './services/auth.service';
import { AuthGuard } from './services/auth.guard.service';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'gallery', component: GalleryComponent, canActivate: [AuthGuard] }
];
#NgModule({
declarations: [
AppComponent,
NavComponent,
HomeComponent,
GalleryComponent,
FooterComponent,
],
imports: [
FormsModule,
BrowserModule,
AppRoutingModule,
NgxCarouselModule,
NgbModule.forRoot(),
ScrollToModule.forRoot(),
RouterModule.forRoot(routes),
AnimateOnScrollModule.forRoot(),
HttpClientModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFireAuthModule,
AngularFireDatabaseModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
exports: [
TranslateModule
],
providers: [AngularFireDatabase, AuthService, AuthGuard],
bootstrap: [AppComponent]
})
auth.guard.ts
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { AngularFireAuth } from 'angularfire2/auth';
import { Injectable, OnInit } from '#angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '#angular/router';
#Injectable()
export class AuthGuard implements CanActivate {
public user = null;
constructor(private fireauth: AngularFireAuth, private router: Router) {
this.fireauth.auth.onAuthStateChanged((user) => {
if (user) {
this.user = this.fireauth.auth.currentUser;
}
});
}
ongOnInit() {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
if (this.user) {
return true;
} else {
this.router.navigate(['']);
return false;
}
}
}
the routes are ok according to me, i thing that the problem most be on the auth guard, i guess.

Try this code
constructor(
private router:Router,
public fireauth:AngularFireAuth
){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
return this.fireauth.authState.map((auth) => {
if(auth == null) {
this.router.navigate(['/']);
return false;
} else {
return true;
}
});
}
i think this.fireauth.auth.onAuthStateChanged is used in older versions

Related

Angular9 'No provided for ActivatedRoute'

I'm beginner in Angular 9. I'm following an online video tutorial to excercise on angular, but my code (same of the tutorial) had a problem and I don't know of to figure out.
Actually, tutorial put routing stuffs all inside app.module.ts, but I use app-routing.module.ts to separate concerns.
When I launch 'ng serve --open', page still blank with the following error:
core.js:6185 ERROR NullInjectorError: R3InjectorError(AppModule)[ActivatedRoute -> ActivatedRoute -> ActivatedRoute]:
NullInjectorError: No provider for ActivatedRoute!
at NullInjector.get (http://localhost:4200/vendor.js:16926:27)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at NgModuleRef$1.get (http://localhost:4200/vendor.js:47971:33)
at Object.get (http://localhost:4200/vendor.js:45804:35)
at getOrCreateInjectable (http://localhost:4200/vendor.js:20704:39)
at Module.ɵɵdirectiveInject (http://localhost:4200/vendor.js:34541:12)
at NodeInjectorFactory.BookComponent_Factory [as factory] (http://localhost:4200/main.js:733:153)
at getNodeInjectable (http://localhost:4200/vendor.js:20849:44)
Actually I had this problem since I use providers. Is it hard to understand, because of console doesn't give any class line code. However I'm trying to describe here useful classes that should use it by following, if more classes needs, I will do that:
--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 { BookComponent } from './components/book/book.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { BooklistComponent } from './components/booklist/booklist.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { TreeComponent } from './components/tree/tree.component';
import { NgInitDirective } from './directive/ng-init/ng-init.directive';
// for angular firebase #https://github.com/angular/angularfire/blob/master/docs/install-and-setup.md
import { AngularFireModule } from '#angular/fire';
import { AngularFirestore } from '#angular/fire/firestore';
import { environment } from '../environments/environment';
// import our service (that uses firebase)
import { CartService } from './services/cart/cart.service'
import { HttpModule } from '#angular/http';
#NgModule({
declarations: [
AppComponent,
BookComponent,
BooklistComponent,
BookEditComponent,
TreeComponent,
NgInitDirective
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase), // have a look in firebase.ts
AngularFireModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
--app-routing.module.ts--
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { BookComponent } from './components/book/book.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { BooklistComponent } from './components/booklist/booklist.component';
const routes: Routes = [
{ path: 'books/:title', component: BookComponent},
{ path: 'books/:title/edit', component: BookEditComponent},
{ path: 'books', component: BooklistComponent},
{
path: '',
redirectTo: 'books/',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
--book.component.ts--
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
import { BookModel } from '../../models/book/book.model';
import { CurrencyPipe } from '#angular/common';
import { ActivatedRoute } from '#Angular/router'
import { CartService } from '../../services/cart/cart.service';
#Component({
selector: 'book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
#Input() book: BookModel;
#Output() addToCart: EventEmitter<BookModel> = new EventEmitter();
constructor(private route: ActivatedRoute, private cs: CartService) {
route.params.subscribe(res => {
this.book = BookModel.find(res['title']);
});
}
ngOnInit(): void {
}
sendToCart() {
this.addToCart.emit(this.book);
// the following method is added in cart.service.ts
this.cs.add(this.book);
}
// methods
votesCounter() {
return this.book.upvotes;
}
upvote() {
return this.book.upvotes++;
}
}
As I use app-routing.module.ts, there is a quite difference in app.module of tutorial (that puts also routing stuffs inside it):
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestore } from 'angularfire2/firestore';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';
import { BookComponent } from './components/book/book.component';
import { BookListComponent } from './components/book-list/book-list.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { TreeComponent } from './components/tree/tree.component';
import { NgInitDirective } from './directive/ng-init/ng-init.directive';
import { CartService } from './services/cart/cart.service';
const bookRoutes: Routes = [
{ path: 'books/:title', component: BookComponent },
{ path: 'books/:title/edit', component: BookEditComponent },
{ path: 'books', component: BookListComponent },
{
path: '',
redirectTo: 'books/',
pathMatch: 'full'
}
]
#NgModule({
declarations: [
AppComponent,
BookComponent,
BookListComponent,
BookEditComponent,
TreeComponent,
NgInitDirective
],
imports: [
RouterModule.forRoot(bookRoutes),
BrowserModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I tryed with solutions given from similar questions, but it doesn't work.
You have a typing error,
change #Angular/router with #angular/router in book.component.ts

Angular 8 basic interceptor not called on page loading

I'm in the process of adding an interceptor to my angular 8 project. To make add bearer token. Unfortunately the interceptor does not seem to be called. My code:
I already:
Added HttpClientModule, HTTP_INTERCEPTORS and HttpConfigInterceptor imports in app.module.ts file.
Added HttpClientModule in imports section after BrowserModule.
Added { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true } in providers section.
app.module.ts file:
import { NgModule } from '#angular/core';
import { BrowserModule, Title } from '#angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { HttpConfigInterceptor } from './httpconfig.interceptor';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HomeComponent } from './home/home.component';
import { PrivacyPolicyComponent } from './privacy-policy/privacy-policy.component';
import { TermsOfUseComponent } from './terms-of-use/terms-of-use.component';
import { SnippetsComponent } from './snippets/snippets.component';
import { SnippetComponent } from './snippet/snippet.component';
import { NotFoundComponent } from './not-found/not-found.component';
#NgModule({
declarations: [
AppComponent,
NavbarComponent,
HeaderComponent,
FooterComponent,
HomeComponent,
PrivacyPolicyComponent,
TermsOfUseComponent,
SnippetsComponent,
SnippetComponent,
NotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [
Title,
{ provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
My interceptor file:
import { Injectable } from '#angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(request);
return next.handle(request);
}
}
I want just the console.log works.
Thks ^^.

How to prompt user when he tries to move out of any component in angular 6

I have a payment page with payment component as -
import { Component, OnInit } from '#angular/core';
import { PayPalConfig, PayPalEnvironment, PayPalIntegrationType } from 'ngx-paypal';
import { AppService } from '../app.service';
import { Payment } from '../models/payment.model';
import { Router } from '#angular/router';
#Component({
selector: 'app-payment',
templateUrl: './payment.component.html',
styleUrls: ['./payment.component.css']
})
export class PaymentComponent implements OnInit {
//totalpay:number;
payment:Payment;
changesSaved=false;
constructor(private appservice:AppService,private router:Router) { }
ngOnInit() {
this.initConfig();
}
hasChanges(){
return true;
} }
Now I want to prompt user if he tries to move back or try to click any link ,without clicking on paypal payment button in payment component ,I have used Candeactivate by making paymentguard.ts
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { PaymentComponent } from './payment/payment.component';
import { PaymentGuard} from './payment/payment.guard';
#Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<PaymentComponent> {
canDeactivate(target: PaymentComponent) {
if (target.hasChanges()) {
return window.confirm('Do you really want to cancel?');
}
return true;
}
}
And this is my routing in app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { BannerComponent } from './banner/banner.component';
import { ProductsComponent } from './products/products.component';
import { BodyComponent } from './body/body.component';
import { BestsellersComponent } from './bestsellers/bestsellers.component';
import { FooterComponent } from './footer/footer.component';
import { BenefitComponent } from './benefit/benefit.component';
import { CombinedComponent } from './combined/combined.component';
import { CartComponent } from './cart/cart.component';
import { StorageServiceModule} from 'angular-webstorage-service';
import { FormsModule } from '../../node_modules/#angular/forms';
import { NgxPayPalModule } from 'ngx-paypal';
import { HttpClientModule } from '#angular/common/http';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { PaymentComponent } from './payment/payment.component';
import { AuthGuard } from './auth.guard';
import { FlashMessagesModule } from 'angular2-flash-messages';
import { FinalstatusComponent } from './finalstatus/finalstatus.component';
import { ConfirmDeactivateGuard } from './payment.guard';
import { PaymentfailComponent } from './paymentfail/paymentfail.component';
const routes: Routes = [
{ path: 'cart', component: CartComponent },
{ path: 'about', component: AboutComponent },
{ path: '', component: CombinedComponent },
{ path: 'payment', component: PaymentComponent,canActivate:[AuthGuard],canDeactivate[ConfirmDeactivateGuard]},
{ path: 'orderstatus', component: FinalstatusComponent,canActivate:[AuthGuard] },
{ path: 'paymentfail', component: PaymentfailComponent,canActivate:[AuthGuard] },
{ path: 'contact', component: ContactComponent },
];
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
BannerComponent,
ProductsComponent,
BodyComponent,
BestsellersComponent,
FooterComponent,
BenefitComponent,
CombinedComponent,
CartComponent,
AboutComponent,
ContactComponent,
PaymentComponent,
FinalstatusComponent,
PaymentfailComponent,
],
imports: [
BrowserModule,
RouterModule.forRoot(routes),
StorageServiceModule,
FormsModule,
NgxPayPalModule,
HttpClientModule,
FlashMessagesModule.forRoot()
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
I don't know why it is not working ,any idea how to achieve it???
Your CanDeactivate route guard must return one of: boolean, Promise, Observable.
In your case, it is best you use the later because your rely on the user taking an action to decide if CanDeactivate care run or not. This makes your guard asynchronous.
Because the method must always return the same type, the !hasChanges() myst also return an observable.
Try this code below:
import { Observable, create } from 'rxjs';
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { PaymentComponent } from './payment/payment.component';
import { PaymentGuard} from './payment/payment.guard';
#Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<PaymentComponent> {
canDeactivate(target: PaymentComponent): Observable<boolean> {
return Observable.create(function(observer) {
if (!target.hasChanges()) {
observer.next(true);
} else if(window.confirm('Do you really want to cancel?')) {
observer.next(true);
} else {
observer.next(false);
}
});
}
}
I hope this helps!
Edit: I moved everything inside of the observer

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.

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.

Categories

Resources