I am trying to navigate to another route after users click a login button. But I can't understand what went wrong. Below is my login component.
import { Component, OnInit } from '#angular/core';
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';
import { Router, ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(public af: AngularFire, private router: Router) {
this.af.auth.subscribe(auth => console.log(auth));
}
login() {
this.af.auth.login({
provider: AuthProviders.Google,
method: AuthMethods.Popup,
}).then(function(res) {
console.log('login success');
console.log(res.uid);
this.router.navigateByUrl('/main') // .then(r => console.log('then: ' + r))
.then(function(resw) {
console.log('has redirect');
})
.catch(err => console.error(err)) ;
console.log('afterward');
}).catch(err => console.error(err));
}
overrideLogin() {
this.af.auth.login({
provider: AuthProviders.Anonymous,
method: AuthMethods.Anonymous,
});
}
ngOnInit() {
}
}
<p>
login works!
</p>
<button (click)="login()">Login With Google</button>
<button (click)="overrideLogin()">Login Anonymously</button>
Here is my routes:
import { LoginComponent } from './login/login.component';
import { MainComponent } from './main/main.component';
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router' ;
const APP_ROUTES: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', pathMatch: 'full', redirectTo: '/login'},
{ path: 'main', component: MainComponent }
];
export const appRoutingProviders: any[] = [
];
export const APP_ROUTES_PROVIDER: ModuleWithProviders = RouterModule.forRoot(APP_ROUTES);
Here is the #NgModule:
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 routing
import { appRoutingProviders, APP_ROUTES_PROVIDER } from './app.routes' ;
#NgModule({
declarations: [
AppComponent,
LoginComponent,
MainComponent
],
imports: [
BrowserModule,
// AngularFireModule.initializeApp(firebaseConfig, myFirebaseAuthConfig), // angularfire setup
FormsModule,
HttpModule,
APP_ROUTES_PROVIDER
],
providers: [appRoutingProviders],
bootstrap: [AppComponent]
})
export class AppModule { }
I got the following error. Can someone please help let me know how to fix this?
TypeError: this is null Stack trace:
LoginComponent</LoginComponent.prototype.login/<#http://localhost:4200/main.bundle.js:70294:13
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke#http://localhost:4200/main.bundle.js:69125:19
NgZoneImpl/this.inner<.onInvoke#http://localhost:4200/main.bundle.js:56178:28
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke#http://localhost:4200/main.bundle.js:69124:19
Zone$1</Zone</Zone.prototype.run#http://localhost:4200/main.bundle.js:69018:24
scheduleResolveOrReject/<#http://localhost:4200/main.bundle.js:69384:52
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask#http://localhost:4200/main.bundle.js:69158:23
NgZoneImpl/this.inner<.onInvokeTask#http://localhost:4200/main.bundle.js:56169:28
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask#http://localhost:4200/main.bundle.js:69157:23
Zone$1</Zone</Zone.prototype.runTask#http://localhost:4200/main.bundle.js:69058:28
drainMicroTaskQueue#http://localhost:4200/main.bundle.js:69290:25
ZoneTask/this.invoke#http://localhost:4200/main.bundle.js:69230:25
Arrow Function(()=>) will resolve issue as every configuration is correct.
login() {
this.af.auth.login({
provider: AuthProviders.Google,
method: AuthMethods.Popup,
}).then((res)=> { //<----changed this line
console.log('login success');
console.log(res.uid);
this.router.navigateByUrl('/main') // .then(r => console.log('then: ' + r))
.then((resw)=> { //<----changed this line
console.log('has redirect');
})
.catch(err => console.error(err)) ;
console.log('afterward');
}).catch(err => console.error(err));
}
this is special in javascript, it depends how the function was called see How to access the correct `this` context inside a callback?.
In type script if you use a fat arrow => it'll cache the this for you eg this.af.auth.login({}).then((res) => {})
Related
I need to use a JavaScript method in my Angular frontend.
I wrote a sort of controller in this way:
import * as commands from 'commands.js'
const http=require('http')
const post = (request) => { return new Promise((resolve, reject) => {
if(request.method === 'POST'){
if(request.url === '/clean'){
commands.clean();
}
}
});
};
const server=http.createServer((req,res) => {
post(req).then(body => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body, null, 2));
}).catch(err => {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({msg: 'Invalid request'}, null, 2));
});
});
server.listen(3000);
Next with ng generate service home I generate a service where i wrote:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class HomeService {
private url = "http://localhost:3000";
private httpHeader=new HttpHeaders({'Access-Control-Allow-Origin':'*'})
constructor(private http:HttpClient) { }
public clear():Observable<any>{
return this.http.post(this.url+"/clean",null,{
headers:this.httpHeader,
responseType:'text'
})
}
}
And then I tryed to use my function clear() in my home.component.ts and I use it like this:
import { Component, OnInit } from '#angular/core';
import {MatCheckboxChange} from "#angular/material/checkbox";
import {HomeService} from "../home.service";
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private homeservice: HomeService) {
}
[...]
async clean(){
this.homeservice.clear()
}
[...]
}
But at this point I found a problem:
When I start my app with
ng serve
My app automatic redirect in /src/home and it show me the html code write in home.component.html. In particular I do this with the default Angular routing module.
In my app-roting.module.ts the code is:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import {HomeComponent} from "./home/home.component";
import {SettingsComponent} from "./settings/settings.component";
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'settings', component: SettingsComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'
},
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
export const routingComponents = [HomeComponent, SettingsComponent]
It works very well but when I add private homeservice: HomeService in the constractor of my home.component.ts, my app tarts to show me the app.component.html white page and I can't do nothing. How can I fix this routing problem?
I think you are missing
<router-outlet></router-outlet>
In your app.component.html
I found the problem, I missed to import in app.module.ts HttpClientModule from #angular/common/http. Now it works.
I have created a route after user logged-in in my angular app (Angular 8). now am trying to write a test case. But its giving below error.
route (/profile) page was not able to call.
Expected spy navigate to have been called with:
[ [ '/profile' ] ]
but it was never called.
login.component.js
import { Component, OnInit } from '#angular/core';
import { UserService } from '../../services/user.service';
import { User } from '../../models/user';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
user: User = new User();
errorMessage: string;
constructor(private userService: UserService, private router: Router){ }
ngOnInit(): void {
if(this.userService.currentUserValue){
this.router.navigate(['/home']);
return;
}
}
login() {
this.userService.login(this.user).subscribe(data => {
this.router.navigate(['/profile']);
}, err => {
this.errorMessage = "Username or password is incorrect.";
});
}
}
login.component.spec.ts
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { LoginComponent } from './login.component';
import { UserService } from 'src/app/services/user.service';
import { Router } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { ExpectedConditions } from 'protractor';
import { DebugElement } from '#angular/core';
import { RouterTestingModule } from '#angular/router/testing';
import { HomeComponent } from '../home/home.component';
import { ProfileComponent } from '../profile/profile.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let debugElement: DebugElement;
let location, router: Router;
let mockRouter;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule, FormsModule ],
declarations: [ LoginComponent, ProfileComponent ],
providers: [UserService]
})
.compileComponents();
}));
beforeEach(() => {
mockRouter = { navigate: jasmine.createSpy('navigate') };
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([
{ path: 'profile', component: ProfileComponent }
])],
declarations: [LoginComponent, ProfileComponent],
providers: [
{ provide: Router, useValue: mockRouter},
]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
});
it('should go profile ', async(() => {
fixture.detectChanges();
component.login();
expect(mockRouter.navigate).toHaveBeenCalledWith(['/profile']);
}));
});
Why are you configuringTestingModule twice?
You should mock userService.
Try:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { LoginComponent } from './login.component';
import { UserService } from 'src/app/services/user.service';
import { Router } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { ExpectedConditions } from 'protractor';
import { DebugElement } from '#angular/core';
import { RouterTestingModule } from '#angular/router/testing';
import { HomeComponent } from '../home/home.component';
import { ProfileComponent } from '../profile/profile.component';
import { of } from 'rxjs'; // import of from rxjs
import { throwError } from 'rxjs'; // import throwError
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let debugElement: DebugElement;
let mockUserService = jasmine.createSpyObj('userService', ['login']);
mockUserService.currentUserValue = /* mock currentUserValue to what it should be */
let router: Router;
beforeEach(async(() => {
// I don't think you need HttpClientTestingModule or maybe FormsModule
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule, FormsModule, RouterTestingModule.withRoutes([
{ path: 'profile', component: ProfileComponent }
])],
declarations: [LoginComponent, ProfileComponent],
providers: [{ provide: UserService, useValue: mockUserService }]
})
.compileComponents();
}));
beforeEach(() => {
router = TestBed.get(Router); // remove the let here !!!!
spyOn(router, 'navigate'); // spy on router navigate
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
});
it('should go profile ', async(() => {
fixture.detectChanges();
mockUserService.login.and.returnValue(of({})); // mock login method on userService when it is called
component.login();
expect(router.navigate).toHaveBeenCalledWith(['/profile']);
}));
it('should set error message on error ', async(() => {
fixture.detectChanges();
mockUserService.login.and.returnValue(throwError('Error')); // mock login method on userService when it is called
component.login();
expect(component.errorMessage).toBe('Username or password is incorrect.');
}));
});
I am working on an Angular 2 project. I am trying to add data-table component in my project. But facing above error at the time of compilation.what needs to be done to get the required output. please guide me in a right direction.
admin-products.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ProductService } from 'src/app/product.service';
import { Subscription } from 'rxjs';
import { Product } from 'src/app/models/product';
import { DataTableResource } from 'angular-4-data-table';
#Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit,OnDestroy {
products: Product[];
filteredProducts: any[];
subscription: Subscription;
tableResource:DataTableResource<Product>;
items: Product[] = [];
itemCount: Number;
constructor(private productService:ProductService) {
this.subscription = this.productService.getAll().
subscribe(products =>{
this.filteredProducts= this.products = products;
this.initializeTable(products);
});
}
private initializeTable(products:Product[]){
this.tableResource.query({ offset:0})
.then(items => this.items = items);
this.tableResource.count()
.then(count => this.itemCount = count);
}
reloadItems(params){
if(!this.tableResource) return;
this.tableResource.query(params)
.then(items => this.items = items);
}
filter(query: string){
this.filteredProducts = (query) ?
this.products.filter(p => p.title.toLowerCase().includes(query.toLowerCase())) :
this.products;
}
ngOnDestroy(){
this.subscription.unsubscribe()
}
ngOnInit() {
}
}
admin-products.component.html
<p>
<a routerLink="/admin/products/new" class="btn btn-primary">New Product</a>
</p>
<p>
<input
#query
(keyup)="filter(query.value)"
type="text" class="form-control" placeholder="Search...">
</p>
<data-table
[items]="items"
[itemCount]="itemCount"
(reload)="reloadItems($event)"
>
<data-table-column
[property]="'title'"
[header]="'title'"
[sortable]="true"
[resizable]="true"
>
<data-table-column
[property]="'price'"
[header]="'Price'"
[sortable]="true"
[resizable]="true"
>
<ng-template #dataTableCell let-item="item">
{{item.price | currency:'USD':true}}
</ng-template>
</data-table-column>
<data-table-column
[property]="'$key'"
>
<ng-template #dataTableCell let-item="item">
<a [routerLink]="['/admin/products', item.$key]">Edit</a>
</ng-template>
</data-table-column>
</data-table>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {RouterModule} from '#angular/router';
import{NgbModule} from '#ng-bootstrap/ng-bootstrap';
import { BsNavbarComponent } from './bs-navbar/bs-navbar.component';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { CheckOutComponent } from './check-out/check-out.component';
import { OrderSuccessComponent } from './order-success/order-success.component';
import { MyOrdersComponent } from './my-orders/my-orders.component';
import { AdminProductsComponent } from './admin/admin-products/admin-products.component';
import { AdminOrdersComponent } from './admin/admin-orders/admin-orders.component';
import { LoginComponent } from './login/login.component';
import {FormsModule} from '#angular/forms';
import {CustomFormsModule} from 'ng2-validation';
import {DataTableModule} from 'angular-4-data-table';
import { AppComponent } from './app.component';
import { environment } from 'src/environments/environment';
import { AuthService } from './auth.service';
import { AuthGuard as AuthGuard } from './auth-guard.service';
import { UserService } from './user.service';
import { AdminAuthGuard as AdminAuthGuard } from './admin-auth-guard.service';
import { ProductFormComponent } from './admin/product-form/product-form.component';
import { CategoryService } from './category.service';
import { ProductService } from './product.service';
#NgModule({
declarations: [
AppComponent,
BsNavbarComponent,
HomeComponent,
ProductsComponent,
ShoppingCartComponent,
CheckOutComponent,
OrderSuccessComponent,
MyOrdersComponent,
AdminProductsComponent,
AdminOrdersComponent,
LoginComponent,
ShoppingCartComponent,
ProductFormComponent
],
imports: [
BrowserModule,
FormsModule,
CustomFormsModule,
DataTableModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
AngularFireAuthModule,
NgbModule.forRoot(),
RouterModule.forRoot([
{path: '', component: HomeComponent},
{path: 'products', component: ProductsComponent},
{path: 'shopping-cart', component: ShoppingCartComponent},
{path: 'login', component: LoginComponent},
{path: 'check-out', component: CheckOutComponent,canActivate:[AuthGuard]},
{path: 'order-success', component: OrderSuccessComponent, canActivate:[AuthGuard]},
{path: 'my/orders',component: MyOrdersComponent,canActivate:[AuthGuard]},
{path: 'admin/products/new', component:ProductFormComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/products/:id', component:ProductFormComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/products', component: AdminProductsComponent,canActivate:[AuthGuard,AdminAuthGuard]},
{path: 'admin/orders', component: AdminOrdersComponent,canActivate:[AuthGuard,AdminAuthGuard]}
])
],
providers: [
AuthService,
AuthGuard,
AdminAuthGuard,
UserService,
CategoryService,
ProductService
],
bootstrap: [AppComponent]
})
export class AppModule { }
should be done to get the required output . please guide me in a right direction
This seems to be related to compiler configuration problems. You're trying to add external components and for that you need to make some modifications to your angular project like in your tsconfig.json file. These usually are provided by the library documentation. See this related question for instance: TypeScript error in Angular2 code: Cannot find name 'module'
However, since you're trying to use a table I would highly recommend you some well known Component Libraries for Angular, all of them have well documented and explained examples:
Angular Material(My favorite) - https://material.angular.io/components/table/examples
Prime NG - https://www.primefaces.org/primeng/#/table
If you decide to do that, just follow the Getting Started of any of them and you should be able to use a well built Table Component and more easily find the solution to related bugs.
I wanna use HttpClientModule to get access Post's Array.
I'm just learning Angular, so could anyone explain to me why this is wrong
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { HatedPostListComponent } from './hated-post-list/hated-post-list.component';
import { HatedAboutUsComponent } from './hated-about-us/hated-about-us.component';
import { HatedLoginComponent } from './hated-login/hated-login.component';
import { DataService } from './services/data.service';
#NgModule({
declarations: [
AppComponent,
HatedPostListComponent,
HatedAboutUsComponent,
HatedLoginComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
import { DataService } from './services/data.service';
import { Post } from './models/user.model';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Frontend';
constructor (private _svc: DataService) {
console.log('Data in component' + this._svc.data);
}
getDate(): Array<Post> {
return this._svc.data;
}
}
data.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Post } from '../models/user.model';
#Injectable()
export class DataService {
baseURL: string;
data: Array<Post> = [];
constructor(private _http: HttpClient) {
this.baseURL = 'http://localhost:5000/Posts?from=0&number=10';
}
getDate() {
this._http.get<Array<Post>>(this.baseURL)
.subscribe(response => {
this.data = response;
console.log('Subcribed data:' + this.data);
console.log('Subcribed response:' + response);
}
);
console.log('Data after subcribe:' + this.data);
}
}
This is what I it
result
When I subcribe() everything is Ok, but after that My data is empty
Change your implementation to following you would get the expected result.
Your Component :
getDate(){
this._svc.getDate().subscribe((res)=> {
console.log(res)
});
}
Your Service :
getDate() {
return this._http.get(this.baseURL);
}
This should work. The issue with your logic is you are just listening to current value of the data from service. where that point of time service holds [], after receiving data from API your component is not notified the change, unless you subscribe to it.
You need to call the service and subscribe in your component not in the service .
Change your service code as,
getDate() {
return this._http.get<Array<Post>>(this.baseURL);
}
and in your component,
getDate(): Array<Post> {
this._svc.getDate().subscribe(
res => {
console.log(res);
},
err => console.log(err)
);
}
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.