ng2: reserve Original value if validation failed - validation

I am trying to force the user to fill in the description when they update an item. It validates, shows error message when validation fails, stops running execution and doesn't update an item.
Please see the series of screenshot below:
However, my item is still updated even if the validation fails. It seems to me that since an object is reference in the memory, it's still updated even if it doesn't run updateTodo() method from the Todoservice.
Is it because I am just hardcoding my items just for the testing? I am very new to Angular and I don't want to implement webAPIs at this point yet.
I tried to use Object.assign({}, copy) in getTodoItem(id: number) to clone and decouple my todoItem from the list but the error message showing that it's not observable.
How can I preserve the values of Objects in the list if the validation fails? In real life application, Since we retrieve the data from the database (or webapi cache) whenever index/list component is navigated, this problem shouldn't occur. Is my assumption right?
todoService.ts
import { Itodo } from './todo'
const TodoItems: Itodo[] = [
{ todoId: 11, description: 'Silencer' },
{ todoId: 12, description: 'Centaur Warrunner' },
{ todoId: 13, description: 'Lycanthrope' },
{ todoId: 14, description: 'Sniper' },
{ todoId: 15, description: 'Lone Druid' }
]
#Injectable()
export class TodoService {
getTodoItems(): Observable<Itodo[]> {
return Observable.of(TodoItems);
}
getTodoItem(id: number): Observable<Itodo> {
return this.getTodoItems()
.map((items: Itodo[]) => items.find(p => p.todoId === id));
//let copy = this.getTodoItems()
// .map((items: Itodo[]) => items.find(p => p.todoId === id));
//return Object.assign({}, copy);
}
addNewTodo(model: Itodo): number {
return TodoItems.push(model); // return new length of an array
}
updateTodo(model: Itodo) : number {
let idx = TodoItems.indexOf(TodoItems.filter(f => f.todoId == model.todoId)[0]);
return TodoItems.splice(idx, 1, model).length; // return the count of affected item
}
}
todo-edit.component.ts -- EditItem() is the main
import { Subscription } from 'rxjs/Subscription';
import { Itodo } from './todo'
import { TodoService } from './todo.service';
#Component({
moduleId: module.id,
templateUrl: "todo-edit.component.html"
})
export class TodoEditComponent implements OnInit, OnDestroy {
todoModel: Itodo;
private sub: Subscription;
Message: string;
MessageType: number;
constructor(private _todoService: TodoService,
private _route: ActivatedRoute,
private _router: Router) {
}
ngOnInit(): void {
this.sub = this._route.params.subscribe(
params => {
let id = +params['id'];
this.getItem(id);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
getItem(id: number) {
this._todoService.getTodoItem(id).subscribe(
item => this.todoModel = item,
error => this.Message = <any>error);
}
EditItem(): void {
this.todoModel.description = this.todoModel.description.trim();
if (!this.todoModel.description) {
this.Message = "Description must not be blank.";
this.MessageType = 2;
return;
}
console.log('valid: update now.');
let result = this._todoService.updateTodo(this.todoModel);
if (result > 0) {
this.Message = "An Item has been updated";
this.MessageType = 1;
}
else {
this.Message = "Error occured! Try again.";
this.MessageType = 2;
}
}
}
Working Solution
Object.assign it's the right method to use. I was using it wrongly in the service to clone it. You need to use it in your component, not in the service.
getItem(id: number) {
//Object.assign clone and decouple todoModel from the ArrayList
this._todoService.getTodoItem(id).subscribe(
item => this.todoModel = Object.assign({}, item),
error => this.Message = <any>error);
}

Validation does not prevent updating items, it just checks actual values for validity. You should create copy of object for editing to be able to rollback changes. You can use Object.assign({}, item) or JSON.parse(JSON.stringify(...)).

Related

Object still frozen when using Immer and NGXS

I am implementing ngxs into an existing codebase.
I have imported Immer and then ngxs bridge in hopes to handle side effects easier.
I've followed every example that I can find through google, I always get:
core.js:6014 ERROR TypeError: Cannot assign to read only property 'savedPrograms' of object '[object Object]'
I've tried using the #ImmutableContext() decorator to accont for this, but I get the exact same error. I also tried using the produce method, but when i give draft.savedPrograms a new value, it throws the error above.
#Action(UserActions.AddProgram)
#ImmutableContext()
public addProgram(ctx: StateContext<UserStateModel>, action) {
ctx.setState(
produce((draft: UserStateModel) => {
draft.user.savedPrograms = action.payload;
})
);
}
The only way i can get this to work is if i use JSON parse/stringify to create a copy of the user and then update the user object.
#Action(UserActions.AddProgram)
public addProgram(ctx: StateContext<UserStateModel>, action) {
const state = produce(draft => {
const copy = JSON.parse(JSON.stringify(draft));
copy.user.savedPrograms.push(action.payload);
draft = copy;
});
ctx.setState(state);
}
I'm not quite sure why ImmutableContext doesn't work out of the box
From immer-adapter documentation:
import { ImmutableContext, ImmutableSelector } from '#ngxs-labs/immer-adapter';
#State<AnimalsStateModel>({
name: 'animals',
defaults: {
zebra: {
food: [],
name: 'zebra'
},
panda: {
food: [],
name: 'panda'
}
}
})
export class AnimalState {
#Selector()
#ImmutableSelector()
public static zebraFood(state: AnimalsStateModel): string[] {
return state.zebra.food.reverse();
}
#Action(Add)
#ImmutableContext()
public add({ setState }: StateContext<AnimalsStateModel>, { payload }: Add): void {
setState((state: AnimalsStateModel) => ({
state.zebra.food.push(payload);
return state;
}));
}
}
As I understand you need to remove produce from your code:
#Action(UserActions.AddProgram)
#ImmutableContext()
public addProgram(ctx: StateContext<UserStateModel>, action) {
ctx.setState(
(draft: UserStateModel) => {
draft.user.savedPrograms = action.payload;
return draft;
}
);
}

SPFX webpart property pane

I am trying to append sharepoint lists in dropdown of spfx webpart property pane. but its not getting appended. please help out.
export default class ScrollTickerWebPart extends BaseClientSideWebPart<IScrollTickerWebPartProps> {
private dropdownOptions: IPropertyPaneDropdownOption[];
private listsFetched: boolean;
private fetchLists(url: string) : Promise<any> {
return this.context.spHttpClient.get(url, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
if (response.ok) {
return response.json();
} else {
console.log("WARNING - failed to hit URL " + url + ". Error = " + response.statusText);
return null;
}
});
}
private fetchOptions(): Promise<IPropertyPaneDropdownOption[]> {
var url = "https://abc.sharepoint.com/teams/SharepointPOC" + "/_api/web/lists?$filter=Hidden eq false";
return this.fetchLists(url).then((response) => {
var options: Array<IPropertyPaneDropdownOption> = new Array<IPropertyPaneDropdownOption>();
response.value.map((list: IODataList) => {
console.log("Found list with title = " + list.Title);
options.push( { key: list.Id, text: list.Title });
});
return options;
});
}
Wherever you call fetchOptions, make sure to call this.context.propertyPane.refresh() after the promise resolves. This is needed to force a re-render of the property pane with the new dropdownOptions.
As an example (somewhere other than onPropertyPaneConfigurationStart is fine as well):
protected onPropertyPaneConfigurationStart(): void {
this.fetchOptions().then(options => {
this.dropdownOptions = options;
this.context.propertyPane.refresh();
});
}
This is assuming that your PropertyPaneDropdown is setup something like below, where this.dropdownOptions are initially undefined, and you are wanting to asynchronously load them with fetchOptions():
PropertyPaneDropdown('someProperty', {
// ...
options: this.dropdownOptions,
// ...
})
Web part properties – dynamically populate Dropdown options in SPFX
we populate the dropdown with the SharePoint lists in the current site. We do this with an async REST call to SharePoint
/* need some imports e.g.:
import { IODataList } from '#microsoft/sp-odata-types';
import { SPHttpClient, SPHttpClientConfigurations,
SPHttpClientConfiguration, SPHttpClientResponse, ODataVersion,
ISPHttpClientConfiguration } from '#microsoft/sp-http';
*/
private dropdownOptions: IPropertyPaneDropdownOption[];
private listsFetched: boolean;
// these methods are split out to go step-by-step, but you could refactor
and be more direct if you choose..
private fetchLists(url: string) : Promise<any> {
return this.context.spHttpClient.get(url,
SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
if (response.ok) {
return response.json();
} else {
console.log("WARNING - failed to hit URL " + url + ". Error = " +
response.statusText);
return null;
}
});
}
private fetchOptions(): Promise<IPropertyPaneDropdownOption[]> {
var url = this.context.pageContext.web.absoluteUrl + `/_api/web/lists?
$filter=Hidden eq false`;
return this.fetchLists(url).then((response) => {
var options: Array<IPropertyPaneDropdownOption> = new
Array<IPropertyPaneDropdownOption>();
response.value.map((list: IODataList) => {
console.log("Found list with title = " + list.Title);
options.push( { key: list.Id, text: list.Title });
});
return options;
});
}
Then in the getPropertyPaneConfiguration method, we kick-off the call to fetch the data at the beginning, and then in the control declaration we simply set the options property to our variable holding the array:
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
if (!this.listsFetched) {
this.fetchOptions().then((response) => {
this.dropdownOptions = response;
this.listsFetched = true;
// now refresh the property pane, now that the promise has been
resolved..
this.onDispose();
});
}
return {
pages: [
{
header: {
description: "Basic settings"
},
groups: [
{
groupName: "COB dropdown field (PropertyPaneDropdown)",
groupFields: [
PropertyPaneDropdown('dropdownProperty', {
label: 'This is the label',
options: this.dropdownOptions
})
]
}
]
}
]
}
}
Refer this Web part properties – dynamically populate Dropdown
You can use PropertyFieldListPicker control which is really easy to use.
This control generates a list picker field that can be used in the property pane of your SharePoint Framework web parts.
The control can be configured as a single or multi-selection list picker. Please check the below link :
https://sharepoint.github.io/sp-dev-fx-property-controls/controls/PropertyFieldListPicker/
You can use PNP PropertyFieldListPicker,
https://pnp.github.io/sp-dev-fx-property-controls/controls/PropertyFieldListPicker/

Stop addEventListener in Angular 6

I have the below code in Angular component
export class ScheduleComponent implements OnInit, OnDestroy {
source:any;
connect(dateValue){
this.source = new
EventSource('http://localhost:8080/api/schedbydate?mydate='+dateValue);
this.source.addEventListener('datarec', datarec => {
let schedule: Notification;
this.schedule = JSON.parse(datarex.data);
}, false);
}
ngOnInit() {
this._erdayService.getErday().subscribe((erday) => {
this._date = erday.text();
this._erdayService.currentMessage.subscribe(message => {
this._date = message;
this.connect(this._date);}
, (error) => { console.error('SERVER ERROR: SELECTED DAY'); });}
, (error) => { console.error('SERVER ERROR:getSchedulesByDate()'); });
}
ngOnDestroy() {
this.source.removeEventListener('message', this.message, false);
//this line doesn't work because I can't access enter variable here!
console.log("Server stopped schedule");
}
}
The issue is the this._date is initially loaded erday and UI view is according to erday. Now when I change the this._date to message, the UI view gets changed.
But still the erday data is shown in UI and the UI view fluctuates between erday & message and I'm not able to stop the this.source.addEventListener().
I tried to destroy in ngOnDestroy(),but it is not working.
I even tried this.source.close();.
Can someone help to know how to stop the listener created before calling another listener on same source ?
You subscribe to 2 data sources that emits continuously :
- The first being this._erdayService.currentMessage
- The second is this.source (when you trigger this.connect())
So this._date will change continuously. So you have to decide which data source you want to keep.
Case 1: You want to keep this.source as your data provider:
export class ScheduleComponent implements OnInit, OnDestroy {
source:any;
sourceListenerSubscription$ : Observable<any>;
connect(dateValue){
this.source = new
EventSource('http://localhost:8080/api/schedbydate?mydate='+dateValue);
this.sourceSubscription$ = Observable.fromEvent(this.source, 'datarec').subscribe( datarec => {
let schedule: Notification;
this.schedule = JSON.parse(datarex.data);
}, false);
}
ngOnInit() {
this._erdayService.getErday().subscribe((erday) => {
this._date = erday.text();
// take only one erday message, then listen to your spring server
this._erdayService.currentMessage.take(1).subscribe(message => {
this._date = message;
this.connect(this._date);}
, (error) => { console.error('SERVER ERROR: SELECTED DAY'); });}
, (error) => { console.error('SERVER ERROR:getSchedulesByDate()'); });
}
ngOnDestroy() {
this.source.removeEventListener('message', this.message, false);
//this line doesn't work because I can't access enter variable here!
console.log("Server stopped schedule");
}
}
Case 2: You want to keep erday as your data provider:
export class ScheduleComponent implements OnInit, OnDestroy {
source:any;
sourceListenerSubscription$ : Observable<any>;
connect(dateValue){
this.source = new
EventSource('http://localhost:8080/api/schedbydate?mydate='+dateValue);
// take date once from spring server, and keep erday as data source
this.sourceSubscription$ = Observable.fromEvent(this.source, 'datarec').take(1).subscribe( datarec => {
let schedule: Notification;
this.schedule = JSON.parse(datarex.data);
}, false);
}
ngOnInit() {
this._erdayService.getErday().subscribe((erday) => {
this._date = erday.text();
this._erdayService.currentMessage.subscribe(message => {
this._date = message;
this.connect(this._date);}
, (error) => { console.error('SERVER ERROR: SELECTED DAY'); });}
, (error) => { console.error('SERVER ERROR:getSchedulesByDate()'); });
}
ngOnDestroy() {
this.source.removeEventListener('message', this.message, false);
//this line doesn't work because I can't access enter variable here!
console.log("Server stopped schedule");
}
}

Admin on rest - implementing aor-realtime

I'm having a real hard time understanding how to implement aor-realtime (trying to use it with firebase; reads only, no write).
The first place I get stuck: This library generates a saga, right? How do I connect that with a restClient/resource? I have a few custom sagas that alert me on errors, but there is a main restClient/resource backing those. Those sagas just handles some side-effects. In this case, I just don't understand what the role of the client is, and how it interacts with the generated saga (or visa-versa)
The other question is with persistence: Updates stream in and the initial set of records is not loaded in one go. Should I be calling observer.next() with each update? or cache the updated records and call next() with the entire collection to-date.
Here's my current attempt at doing the later, but I'm still lost with how to connect it to my Admin/Resource.
import realtimeSaga from 'aor-realtime';
import { client, getToken } from '../firebase';
import { union } from 'lodash'
let cachedToken
const observeRequest = path => (type, resource, params) => {
// Filtering so that only chats are updated in real time
if (resource !== 'chat') return;
let results = {}
let ids = []
return {
subscribe(observer) {
let databaseRef = client.database().ref(path).orderByChild('at')
let events = [ 'child_added', 'child_changed' ]
events.forEach(e => {
databaseRef.on(e, ({ key, val }) => {
results[key] = val()
ids = union([ key ], ids)
observer.next(ids.map(id => results[id]))
})
})
const subscription = {
unsubscribe() {
// Clean up after ourselves
databaseRef.off()
results = {}
ids = []
// Notify the saga that we cleaned up everything
observer.complete();
}
};
return subscription;
},
};
};
export default path => realtimeSaga(observeRequest(path));
How do I connect that with a restClient/resource?
Just add the created saga to the custom sagas of your Admin component.
About the restClient, if you need it in your observer, then pass it the function which return your observer as you did with path. That's actually how it's done in the readme.
Should I be calling observer.next() with each update? or cache the updated records and call next() with the entire collection to-date.
It depends on the type parameter which is one of the admin-on-rest fetch types:
CRUD_GET_LIST: you should return the entire collection, updated
CRUD_GET_ONE: you should return the resource specified in params (which should contains its id)
Here's the solution I came up with, with guidance by #gildas:
import realtimeSaga from "aor-realtime";
import { client } from "../../../clients/firebase";
import { union } from "lodash";
const observeRequest = path => {
return (type, resource, params) => {
// Filtering so that only chats are updated in real time
if (resource !== "chats") return;
let results = {}
let ids = []
const updateItem = res => {
results[res.key] = { ...res.val(), id: res.key }
ids = Object.keys(results).sort((a, b) => results[b].at - results[a].at)
}
return {
subscribe(observer) {
const { page, perPage } = params.pagination
const offset = perPage * (page - 1)
const databaseRef = client
.database()
.ref(path)
.orderByChild("at")
.limitToLast(offset + perPage)
const notify = () => observer.next({ data: ids.slice(offset, offset + perPage).map(e => results[e]), total: ids.length + 1 })
databaseRef.once('value', snapshot => {
snapshot.forEach(updateItem)
notify()
})
databaseRef.on('child_changed', res => {
updateItem(res)
notify()
})
const subscription = {
unsubscribe() {
// Clean up after ourselves
databaseRef.off();
// Notify the saga that we cleaned up everything
observer.complete();
}
};
return subscription;
}
};
}
};
export default path => realtimeSaga(observeRequest(path));

How to working with data from client side using Observables

I am using the Grid of Kendo (Angular 2) for Add/Edit/Delete a Row in the grid:
http://www.telerik.com/kendo-angular-ui/components/grid/editing/
In the original Code, the data is obtained from a rest service like this:
private fetch(action: string = "", data?: Product): Observable<Product[]> {
return this.jsonp
.get(`http://demos.telerik.com/kendo-ui/service/Products/${action}? callback=JSONP_CALLBACK${this.serializeModels(data)}`)
.map(response => response.json());
}
But, I want to work with a array for add/edit/delete rows in memory. Next, I want to do click in the button submit and send the data (with all my changes) to the server.
My solution for this is like this:
https://gist.github.com/joedayz/9e318a47d06a7a8c2170017eb133a87e
Overview:
I declare an array:
private view: Array = [{ProductID: 1, ProductName: "pelotas", Discontinued: undefined, UnitsInStock: 80}];
and override the fetch method like this:
private fetch(action: string = "", data?: Product): Observable<Product[]> {
/*return this.jsonp
.get(`http://demos.telerik.com/kendo-ui/service/Products/${action}?callback=JSONP_CALLBACK${this.serializeModels(data)}`)
.map(response => response.json());*/
debugger;
if(action=="create"){
var product : Product = new Product(-1, data.ProductName, data.Discontinued, data.UnitsInStock);
this.view.push(product);
}else if(action=="update"){
var indice = this.view.indexOf(data);
if(indice>=0)
this.view[indice] = (JSON.parse(JSON.stringify(data)));
}else if(action=="destroy"){
var indice = this.view.indexOf(data);
if(indice>=0)
this.view.splice(indice, 1);
}
return Observable.of(this.view);
}
My Question is: Exists some way of communicate the create/update/delete of items in my array of a simple or reactive form to my grid?
As you are using in-memory array you do not need to use Observables. The Grid component is already bound to the array, thus it is just necessary to manipulate the data. For example:
export class AppComponent {
public dataItem: Product;
#ViewChild(GridEditFormComponent) protected editFormComponent: GridEditFormComponent;
private view: Array<Product> = [{ ProductID: 1, ProductName: "pelotas", Discontinued: undefined, UnitsInStock: 80 }];
public onEdit(dataItem: any): void {
this.dataItem = Object.assign({}, dataItem);
}
public onCancel(): void {
this.dataItem = undefined;
}
public addProduct(): void {
this.editFormComponent.addProduct();
}
public onSave(product: Product): void {
if (product.ProductID === undefined) {
this.createProduct(product);
} else {
this.saveProducts(product);
}
}
public onDelete(e: Product): void {
this.deleteProduct(e);
}
public saveProducts(data: Product): void {
var index = this.view.findIndex(x => x.ProductID === data.ProductID);
if (index !== -1) {
this.view = [
...this.view.slice(0, index),
data,
...this.view.slice(index + 1)
];
}
}
public createProduct(data: Product): void {
this.view = [...this.view, data];
}
public deleteProduct(data: Product): void {
this.view = this.view.filter(x => x.ProductID !== data.ProductID);
}
}

Resources