Skip to content

Commit c19664b

Browse files
committed
Guard and update create service created
1 parent ff4c8ea commit c19664b

5 files changed

+162
-32
lines changed

src/app/app.module.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { ProductServiceService } from './ram/product/product-service.service';
2828
import { SearchFilterPipe } from './share/custome/filter.pipe';
2929
import { StarRatingComponent } from './share/star-rating-component/star-rating-component';
3030
import { CapitalizePipe } from './share/custome/capitalizefirst.pipe';
31+
import { ProductEditGuard } from './ram/product/product-guard.service';
3132

3233

3334

@@ -58,7 +59,9 @@ import { CapitalizePipe } from './share/custome/capitalizefirst.pipe';
5859
{ path: 'home', component: HomeComponent },
5960
{ path: 'product', component: ProductListComponent },
6061
{ path: 'product/:id', component: ProductDetailsComponent },
61-
{ path: 'product/:edit/:id', component: ProductAddEditComponent },
62+
{ path: 'product/:edit/:id',
63+
canDeactivate : [ProductEditGuard],
64+
component: ProductAddEditComponent },
6265
{ path: 'sign-up', component: SignUpFormComponent },
6366
{ path: 'client-register', component: RegisterClientComponent },
6467
{ path: 'contact', component: ContactComponent },
@@ -70,7 +73,8 @@ import { CapitalizePipe } from './share/custome/capitalizefirst.pipe';
7073
FormsModule
7174
],
7275
providers: [
73-
ProductServiceService
76+
ProductServiceService,
77+
ProductEditGuard
7478
],
7579
bootstrap: [AppComponent]
7680
})

src/app/ram/product/product-add-edit/product-add-edit.component.html

+26-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<div class='panel panel-primary'>
22
<div class='panel-heading'>
3-
<span *ngIf="moviesDetails">Edit Movie {{moviesDetails.title | capitalizeFirst : true}} </span>
3+
<span *ngIf="moviesDetails"> {{pageTitle | capitalizeFirst : true}} </span>
44
</div>
55
<div class='panel-body'>
66
<div class="row">
@@ -151,16 +151,33 @@
151151
</span>
152152
</div>
153153
</div>
154-
<div class="form-group">
155-
<label class="col-md-2" for="">Tags:-</label>
156-
<div class="col-md-8">
157-
<input type="text"
158-
id=""
159-
formControlName="tags"
160-
placeholder="Tags"
161-
class="form-control" />
154+
155+
<div formArrayName="tags">
156+
<div class="row">
157+
<button class="col-md-offset-1 col-md-1 btn btn-primary"
158+
type="button"
159+
(click)="addTag()">
160+
Add Tag
161+
</button>
162162
</div>
163+
<div class="form-group"
164+
*ngFor="let tag of tags.controls; let i=index">
165+
<label class="col-md-2"
166+
[attr.for]="i">Tags:-</label>
167+
<div class="col-md-8">
168+
<input type="text"
169+
[id]="i"
170+
[formControlName]="i"
171+
placeholder="Tags"
172+
class="form-control" />
173+
</div>
174+
</div>
175+
163176
</div>
177+
178+
179+
180+
164181
<div class="form-group">
165182
<div class="col-md-8 col-md-offset-2">
166183
<button [disabled]='!movieForm.valid' class="btn btn-primary pull-right" type="submit"><i class='fa fa-save'></i> Save</button>

src/app/ram/product/product-add-edit/product-add-edit.component.ts

+71-5
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import 'rxjs/add/observable/merge';
99
import { Observable } from 'rxjs/Observable';
1010
import { Subscription } from 'rxjs/Subscription';
1111

12+
import { IProduct } from '../products';
1213
import { ProductServiceService } from '../product-service.service';
1314
import { GenericValidatorForms } from '../../../share/custome/generic.validator.forms';
1415
import { NumberValidators } from '../../../share/custome/number.validators';
@@ -22,11 +23,11 @@ export class ProductAddEditComponent implements OnInit, AfterViewInit, OnDestroy
2223

2324
@ViewChildren(FormControlName, { read: ElementRef }) formInputElements: ElementRef[];
2425

25-
pageTitle:string = 'Page Title ';
26+
pageTitle:string = '';
2627
rank:number;
2728
imgwidth:number = 100;
2829
errorMessage: string;
29-
moviesDetails:any[];
30+
moviesDetails:IProduct;
3031
private sub:Subscription;
3132

3233
movieForm:FormGroup;
@@ -35,6 +36,12 @@ export class ProductAddEditComponent implements OnInit, AfterViewInit, OnDestroy
3536
displayMessage: { [key: string]: string } = {};
3637
private validationMessages: { [key: string]: { [key: string]: string } };
3738
private genericValidator: GenericValidatorForms;
39+
40+
get tags(): FormArray {
41+
return <FormArray>this.movieForm.get('tags');
42+
}
43+
44+
3845
constructor(
3946
private _route: ActivatedRoute,
4047
private _router: Router,
@@ -103,7 +110,7 @@ export class ProductAddEditComponent implements OnInit, AfterViewInit, OnDestroy
103110
budget:['', Validators.required],
104111
worldwideGross:['', Validators.required],
105112
rating:['', NumberValidators.range(1, 5)],
106-
tags:['']
113+
tags: this._fb.array([]),
107114

108115
})
109116

@@ -138,11 +145,48 @@ export class ProductAddEditComponent implements OnInit, AfterViewInit, OnDestroy
138145
this._service.getProductDetail(id).subscribe(
139146
data => {
140147
console.log(data);
141-
this.moviesDetails = data;
148+
149+
//this.moviesDetails = data;
150+
this.onMovieRetrieved(data);
142151
},
143152
error => this.errorMessage = <any>error);
144153
}
145154

155+
onMovieRetrieved(data):void{
156+
console.log(data);
157+
// here set to data
158+
if (this.movieForm) {
159+
this.movieForm.reset();
160+
}
161+
// here set to data fill
162+
this.moviesDetails = data;
163+
164+
if (this.moviesDetails.id === 0) {
165+
this.pageTitle = 'Add Movies ';
166+
} else {
167+
this.pageTitle = `Edit Movies: ${this.moviesDetails.title}`;
168+
}
169+
170+
// Update the data on the form
171+
this.movieForm.patchValue({
172+
title: this.moviesDetails.title,
173+
distributor: this.moviesDetails.distributor,
174+
directedBy: this.moviesDetails.directedBy,
175+
producedBy: this.moviesDetails.producedBy,
176+
storyBy: this.moviesDetails.storyBy,
177+
starring: this.moviesDetails.starring,
178+
releaseDate: this.moviesDetails.releaseDate,
179+
runningTime: this.moviesDetails.runningTime,
180+
budget: this.moviesDetails.budget,
181+
worldwideGross: this.moviesDetails.worldwideGross,
182+
rating: this.moviesDetails.rating
183+
});
184+
this.movieForm.setControl('tags', this._fb.array(this.moviesDetails.tags || []));
185+
}
186+
187+
addTag(): void {
188+
this.tags.push(new FormControl());
189+
}
146190
onBack():void{
147191
this._router.navigate(['/product']);
148192
}
@@ -153,7 +197,29 @@ export class ProductAddEditComponent implements OnInit, AfterViewInit, OnDestroy
153197

154198
formUpdate() :void{
155199
console.log('click to form update ');
156-
console.log(this.movieForm);
200+
// console.log(this.movieForm);
201+
if (this.movieForm.dirty && this.movieForm.valid) {
202+
// Copy the form values over the product object values
203+
let movieFormValue = Object.assign({}, this.moviesDetails, this.movieForm.value);
204+
205+
console.log(movieFormValue);
206+
this._service.saveDetailsData(movieFormValue)
207+
.subscribe(
208+
() => this.onSaveComplete(),
209+
(error: any) => this.errorMessage = <any>error
210+
);
211+
}
212+
else if (!this.movieForm.dirty) {
213+
this.onSaveComplete();
214+
}
215+
}
216+
217+
onSaveComplete(): void {
218+
console.log('save completed form call');
219+
// Reset the form to clear the flags
220+
this.movieForm.reset();
221+
this._router.navigate(['/product']);
157222
}
158223

224+
159225
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { Injectable } from '@angular/core';
2+
import { ActivatedRouteSnapshot, Router, CanDeactivate } from '@angular/router';
3+
4+
import { ProductAddEditComponent } from '../product/product-add-edit/product-add-edit.component';
5+
6+
7+
@Injectable()
8+
export  class ProductEditGuard implements CanDeactivate<ProductAddEditComponent> {
9+
10+
canDeactivate(component: ProductAddEditComponent): boolean {
11+
if (component.movieForm.dirty) {
12+
let title = component.movieForm.get('title').value || 'New Product';
13+
return confirm(`Navigate away and lose all changes to ${title}?`);
14+
}
15+
return true;
16+
}
17+
}

src/app/ram/product/product-service.service.ts

+42-16
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,43 @@ export class ProductServiceService {
3030
if (id === 0) {
3131
// return Observable.of(this.initializeProduct());
3232
return Observable.create((observer: any) => {
33-
observer.next(this.initializeProduct());
34-
observer.complete();
33+
observer.next(this.initializeProduct());
34+
observer.complete();
3535
});
3636
};
37-
const url = `${this.baseUrl}/${id}`;
38-
return this.http.get(url)
37+
const url = `${this.baseUrl}/${id}`;
38+
return this.http.get(url)
3939
.map(this.extractData)
4040
.do(data => console.log('getProductDetail: ' + JSON.stringify(data)))
4141
.catch(this.handleError);
42-
43-
42+
43+
44+
}
45+
46+
// data update save service here
47+
saveDetailsData(product: IProduct): Observable<IProduct> {
48+
let headers = new Headers({ 'Content-Type': 'application/json' });
49+
let options = new RequestOptions({ headers: headers });
50+
51+
if (product.id === 0) {
52+
return this.createList(product, options);
53+
}
54+
return this.updateList(product, options);
55+
}
56+
57+
private createList(product: IProduct, options: RequestOptions): Observable<IProduct> {
58+
product.id = undefined;
59+
return this.http.post(this.baseUrl, product, options)
60+
.map(this.extractData)
61+
.do(data => console.log('createList: ' + JSON.stringify(data)))
62+
.catch(this.handleError);
63+
}
64+
private updateList(product: IProduct, options: RequestOptions): Observable<IProduct> {
65+
const url = `${this.baseUrl}/${product.id}`;
66+
return this.http.put(url, product, options)
67+
.map(() => product)
68+
.do(data => console.log('updateList: ' + JSON.stringify(data)))
69+
.catch(this.handleError);
4470
}
4571

4672

@@ -59,22 +85,22 @@ export class ProductServiceService {
5985
initializeProduct(): IProduct {
6086
// Return an initialized object
6187
return {
62-
id:0,
88+
id: 0,
6389
rank: null,
6490
title: null,
6591
distributor: null,
6692
tags: [''],
6793
worldwideGross: null,
6894
img: null,
69-
rating : null,
70-
directedBy :null,
71-
producedBy:null,
72-
storyBy:null,
73-
starring:null,
74-
releaseDate:null,
75-
runningTime:null,
76-
budget:null
95+
rating: null,
96+
directedBy: null,
97+
producedBy: null,
98+
storyBy: null,
99+
starring: null,
100+
releaseDate: null,
101+
runningTime: null,
102+
budget: null
77103
};
78-
}
104+
}
79105

80106
}

0 commit comments

Comments
 (0)