canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return new Promise((resolve, reject) => {
this.securityService.securityActions().subscribe(
data => {debugger;
if(data = this.authorized.find(k => k=='AGREEMENTS_VIEW','AGREEMENTS_INSERT_UPDATE')){
resolve(true);
}
if(data != this.authorized){
resolve(false);
}
},
error => {
Utils.notifyErrors(error, this.notificationsService);
}
)
});
}
I want to set true if data contains some items of "authorized".
Authorized is formed like this:
authorized = [
'AGREEMENTS_VIEW',
'PROSPECTS_VIEW',
'AGREEMENTS_INSERT_UPDATE',
'PRODUCTS_INSERT_UPDATE',
'PROSPECTS_INSERT_UPDATE',
'DOCUMENTS_VIEW',
'DOCUMENTS_INSERT_UPDATE',
];
So for example set true if data contains 'AGREEMENTS_VIEW'.
Right now if i set 2 value on K it doesnt work
Use some, which returns true if the condition is matched.
return arrayOne.some(itemOfArrayOne => arrayTwo.includes(itemOfArrayOne));
You can replace includes with indexOf(XXX) !== -1.
It seems you have a syntax error:
data === this.authorized.find(k => k=='AGREEMENTS_VIEW')
//---^^^-----here
Related
I have a list in angular, an array. OnInit it gets filled from the right corresponding database items. I created a form above it. When you enter something in the form, it acts like a filter. This works, the first time. When you erase something from the form and enter something else, the list should be refreshed and afterwards filtered based on the new input. This doesn't happen. I put the formula that happens on onInit in my function to refill the list.
Below you can find my function (I left the console logs in) and a screenshot of the problem. First I look for a user (joeri.boons#hi10.be) which returns three results. Than I erase the user and look based on a month 7. The screen returns a new unfilterd list while in the console it still holds the list of 3 x user joeri.boons#hi10.be. So there is an inconsistency to. If you look at screen result you would think of a filter problem, the console points at a refreshproblem.
if more code is required let me know.
updateWithFilter(): void {
console.log("function update filter reached")
console.log(this.listadapted);
if(this.listadapted == true){
// this.timesheetsHandled = {} as TimeSheet[];
this.getHandledSheet();
console.log("getHandledSheet executed")
}
if(this.filterUsername.trim() && !this.filterYear && !this.filterMonth){
console.log("option 1 reached")
console.log(this.filterUsername.trim());
console.log(this.filterYear);
console.log(this.filterMonth);
this.timesheetsHandled = this.timesheetsHandled.filter(sheet => sheet.username == this.filterUsername);
this.listadapted = true;
} else if(!this.filterUsername.trim() && !this.filterYear && this.filterMonth){
console.log("option 2 reached");
console.log(this.filterUsername.trim());
console.log(this.filterYear);
console.log(this.filterMonth);
console.log("before filter");
this.timesheetsHandled.forEach(sheet => console.log(sheet.username));
this.timesheetsHandled = this.timesheetsHandled.filter(sheet => sheet.month == this.filterMonth);
console.log("after filter");
this.timesheetsHandled.forEach(sheet => console.log(sheet.username));
// console.log(this.timesheetsHandled.filter(sheet => sheet.month == this.filterMonth));
this.listadapted = true;
} else if .. more options
}
ngOnInit(): void {
this.getHandledSheet();
}
getHandledSheet(): void {
this.timesheetService.getAllTimesheets().subscribe({next: (response: TimeSheet[]) => {this.timesheetsHandled = response.filter(sheet => sheet.status == 'HANDLED') }}) ;
}
My guess would be that this is caused by loading data in ngOnInit. As the documentation (https://angular.io/api/core/OnInit) states : [...] It is invoked only once when the directive is instantiated.
I suspect that you create one instance and re-use it and the ngOnInit method does not get called again.
UPDATE:
The issue is that the call to this.getHandledSheet(); does a call to .. .subscribe({next: .. which is delayed and the rest of the function is executed first.
So the actual code after next: is only executed after the timeSheetService is done loading the data.
So either you apply the filter in the
{next: (response: TimeSheet[]) => {this.timesheetsHandled = response.filter(sheet => sheet.status == 'HANDLED') }}
block after filtering for 'HANDLED' or you'll try to await in the update function.
Create two variables, one that will always remain unfiltered, then another that will be filtered.
The problem will be that the original list is filtered, hence you are losing the original data after filtering!
timesheetHandled: TimeSheet[];
timesheetHandledOriginal: TimeSheet[];
updateWithFilter(): void {
console.log('function update filter reached');
console.log(this.listadapted);
if (this.listadapted == true) {
// this.timesheetsHandled = {} as TimeSheet[];
this.getHandledSheet();
console.log('getHandledSheet executed');
}
if (this.filterUsername.trim() && !this.filterYear && !this.filterMonth) {
console.log('option 1 reached');
console.log(this.filterUsername.trim());
console.log(this.filterYear);
console.log(this.filterMonth);
this.timesheetsHandled = this.timesheetHandledOriginal.filter(
sheet => sheet.username == this.filterUsername
);
this.listadapted = true;
} else if (!this.filterUsername.trim() && !this.filterYear && this.filterMonth) {
console.log('option 2 reached');
console.log(this.filterUsername.trim());
console.log(this.filterYear);
console.log(this.filterMonth);
console.log('before filter');
this.timesheetsHandled.forEach(sheet => console.log(sheet.username));
this.timesheetsHandled = this.timesheetHandledOriginal.filter(
sheet => sheet.month == this.filterMonth
);
console.log('after filter');
this.timesheetsHandled.forEach(sheet => console.log(sheet.username));
// console.log(this.timesheetsHandled.filter(sheet => sheet.month == this.filterMonth));
this.listadapted = true;
}
// else if .. more options
}
ngOnInit(): void {
this.getHandledSheet();
}
getHandledSheet(): void {
this.timesheetService.getAllTimesheets().subscribe({
next: (response: TimeSheet[]) => {
this.timesheetsHandled = response.filter(sheet => sheet.status == 'HANDLED');
this.timesheetHandledOriginal = JSON.parse(JSON.stringify(this.timesheetsHandled));
},
});
}
I have a problem that I can't solve. Here is the thing. As a result of iteration, for each item I get one array with one object inside. I would like it to be one array that has all object items inside in order for further mapping and filtering. Later I'll need it to be json.
console.log(data)
[...][...] ... [...] // result
I want:
{ [...], [...] ... [...] } // this I want
I tried push, join, merge and spread operator without any luck.
code:
const body = [];
const result = await fetch(uls, options);
body.push({
textBody: await result.text(),
url: i.contentUrl,
});
const allAddedHashtags = body
.map((i) => {
const searchFor = /([+]hashtags: [^\n]*(\n+))/g;
return {
hashtags: i.textBody.match(searchFor),
url: i.url,
};
})
.filter((i) => i.hashtags !== null && i.hashtags.length === 2)
.map((i) => {
return {
original: i.hashtags[0]
.replace(/[+]hashtags: "/g, "")
.replace(/"\n/g, "")
.split(",")
.sort(),
edited: i.hashtags[1]
.replace(/[+]hashtags: "/g, "")
.replace(/"\n/g, "")
.replace(/\n/g, "")
.replace(/##/g, "#")
.replace(/ #/g, "#")
.replace(/"#/g, "#")
.replace(/\"/g, "")
.split(",")
.sort(),
url: i.url,
};
})
.map((i) => {
return {
keep: i.edited.filter((x) => !new Set(i.original).has(x)),
url: i.url,
};
});
this is my code:
getSetting() {
Loading.show();
const data = {
vendorId: JSON.parse(localStorage.getItem("TOKEN_DATA_MAGIC")).user
.vendorId,
};
this.api.getSetting(data).subscribe(
(data) => {
console.log(data);
let res: any = data;
if (res.setting != "not found") {
const res: any = data;
this.settingItem.Selling_Type = res.setting
? res.setting.Selling_Type
: null;
this.settingItem.Closing_hours = res.setting.Closing_hours;
this.settingItem.Shipping = res.setting.Shipping;
this.settingItem.Packaging = res.setting.Packaging;
setTimeout(() => Loading.hide(), 1000);
let msg = "تنظیمات دریافت شد";
this.toastr.show(msg, "تنظیمات");
}
},
(err) => {
console.log(err);
let errMsg = "خطا رح داد لاگ را نگاه کنید";
let errFullMsg = "خطا در لاگ مرورگر";
let errFullMessage = err.error.message ? err.error.message : errFullMsg;
this.toastr.success(errFullMessage, errMsg);
}
);
}
sometimes this returned object is: {}
and when i seek in console the value is {}
how can i detect it? when this value is an empty object
You can use Object.keys()
if(Object.keys(obj).length === 0) { //Object is empty }
You can use object.entries() function, Its used like this
Object.entries(objectToCheck)
If it returns an empty array, means it is empty ( returning empty array means the object does not have any enumerable property).
Object.entries(objectToCheck).length === 0
then do your required set of tasks.
For checking if object is really an object you can check if its constructor is the Object object like below
objectToCheck.constructor === Object
I am trying to store values in AsyncStorage as array, but values are not saving there and getting nothing when i try to get the values from array.Any help would be appreciated.Thank you in advance,here is my code :
let searchString = this.state.inputValue
AsyncStorage.getItem('searches', (res) => {
var searches
if (res === null) {
searches = []
}else {
searches = JSON.parse(res)
}
searches.push({
searchString: searchString
})
AsyncStorage.setItem('searches', JSON.stringify(searches), (res) => {
console.log('====FirstPage====setItem==async==='+res)
})
});
//getting values from asyncstorage :
AsyncStorage.getItem('searches', (res) => {console.log('===res==='+res)})
Please try this
AsyncStorage.getItem("searches").then((value) => {
this.setState({"searches": value});
}).done();
Also see
https://www.thepolyglotdeveloper.com/2015/09/saving-data-in-your-react-native-mobile-application/
You can store the data as following:
AsyncStorage.setItem('searches', JSON.stringify(searchString));
In order to fetch/get, you can do that using following:
AsyncStorage.getItem('searches', (err, result) => { // err indicating the error
console.log("Storage Data(String):", result); // print is string format
console.log("Storage Data(Object):", JSON.parse(result)); // print is json format
})
I am trying to use this filter in an angular+ngrx app:
fetchById(id: number): Document {
return this.store.select( s => s.documents ).filter( obj => obj.id == id )[0]
}
documents is an array of Documents, and the latter have an id property. The idea is to filter the array to select one document. However, I get this error message:
Property id does not exist on type Document[]. I don't understand the message, since obj is an element of the array, hence a certain object which has an id property. Any ideas on what is wrong here? Thanks!
Let's break down the operations to understand what's going on...
fetchById(id: number): Observable<Document> {
const documents: Observable<Document[]> = this.store.select(s => s.documents);
const filtered: Observable<Document[]> = documents.filter((obj: Document[]) => obj.id == id );
const result: Observable<Document> = filtered.first();
return result;
}
Notice that Observable#filter()'s callback takes an array, not an individual item. This is different from Array#filter() and the cause of the error message. Also, see that I can't retrieve the first item from an observable with [0], use first() instead. Then I changed the return type to return an observable.
Yet, it doesn't work. When we think about filtering an array from an observable, probably we want to use Observable#map() to produce another array with a single element.
fetchById(id: number): Observable<Document> {
return this.store
.select(s => s.documents)
.map(list => obj.find(obj => obj.id === id));
.first();
}
If we want to return the last value of the observable, we can do this:
fetchById(id: number): Document | null {
let result: Document | null = null;
this.store
.select(s => s.documents)
.map(list => obj.find(obj => obj.id === id) || null);
.first()
.subscribe(item => result = item);
return result;
}
I typed it with | null because the document with the specified id may not exist.