I have a auth.service and data.service. auth.service getting data from data.service but it checks before data arrives. So it returns undefined.
auth.service getting data like this;
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
const emailVerify = this.dataservice.userStatService(user.uid);
console.warn(emailVerify)
return (user !== null && emailVerify !== false && emailVerify !== undefined ) ? true : false;
}
data.service check user status function like this;
userStatService(uid: any): any{
console.error(uid)
this.get(uid)
.subscribe(
data => {
console.warn('status set', data.status)
this.statData = data.status;
},
error => {
console.log(error);
});
return this.statData;
}
and this code works like this now;
See console logs
I'm waiting for your code examples, thank you.
Update:
auth.guard code;
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.isLoggedIn() !== true) {
this.router.navigate(['/auth/login'], { queryParams: { returnUrl: 'dashboard' } })
.then(() => {
this.authService.SignOut();
});
}else{
return true;
}
}
observables execute asynchronously, you need to return the observable and subscribe in the consumer to use it correctly:
// return observable
userStatService(uid: any): any{
console.error(uid)
return this.get(uid)
}
isLoggedIn() {
const user = JSON.parse(localStorage.getItem('user'));
this.dataservice.userStatService(user.uid).subscribe(emailVerify => {
console.warn(emailVerify)
})
// really can't do this while working with async execution. doesn't work.
//return (user !== null && emailVerify !== false && emailVerify !== undefined ) ? true : false;
}
if this is for a guard, use the map operator and return the whole observable, angular expects either a boolean or an observable:
isLoggedIn(): Observable<boolean> {
const user = JSON.parse(localStorage.getItem('user'));
if (!user)
return of(false); // null guard and slight performance improvement
return this.dataservice.userStatService(user.uid).pipe(map(emailVerify => {
console.warn(emailVerify)
return (emailVerify !== false && emailVerify !== undefined ) ? true : false;
}))
}
and in your guard you need to again, RETURN THE OBSERVABLE:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isLoggedIn().pipe(
map(isLoggedIn => {
if (!isLoggedIn) {
this.router.navigate(['/auth/login'], { queryParams: { returnUrl: 'dashboard' } }).then(() => {
this.authService.SignOut();
});
}
return isLoggedIn;
})
)
}
angular guards will handle the subscribing, but you must return the observable to the guard.
Related
I am new to Angular and i am facing some difficulties with a task. I have an array of IDs that i want to execute the same GET Call over. And for every GET call result i have to do some operations and then add the result of every operation to some arrays. I managed to find a way to do it correctly. But my problem is, i can't manage to wait for the final result to be ready (after all the GET calls are done and the operations too) before giving it as an argument to another method that will send it with a POST call.
the method where i do the GET calls and the operations over every call's result (the problem occurs when i am in the rollBackSPN condition).
async getComponentIds(taskName: String, selectedComponents: IComponent[]) {
const componentsId: number[] = [];
const componentsWithoutParams: IComponent[] = [];
let sendPortaPrecedente : boolean;
if(taskName == "rollBackSPN"){
from(selectedComponents).pipe(
concatMap(component =>{
return this.http.get<any>("Url"+component.idComponent).pipe(
tap(val => {
sendPortaPrecedente = true;
for(const obj of val){
if((obj.name == "z0bpqPrevious" && obj.value == null) || (obj.name == "datePortaPrevious" && obj.value == null) || (obj.name == "typePortaPrevious" && obj.value == null)){
sendPortaPrecedente = false;
}
}
if(sendPortaPrecedente){
componentsId.push(component.idComponent);
}else{
componentsWithoutParams.push(component);
}
}),
catchError(err => {
return of(err);
})
)
})
).subscribe(val => {
return { componentsId : componentsId, componentsWithoutParams : componentsWithoutParams, sendPortaPrecedente : sendPortaPrecedente};
});
}else{
for (const component of selectedComponents) {
componentsId.push(component.idComponent)
return { componentsId : componentsId, componentsWithoutParams : componentsWithoutParams, sendPortaPrecedente : sendPortaPrecedente};
}
}
}
The method where i pass the getComponentIds(taskName: String, selectedComponents: IComponent[]) result so it can be send with a POST call (again when i am in the rollBackSPN condition)
executeTask(serviceIdSi: string, actionIdSi: string, actionClassName: string, componentName: string, taskName: string,
componentsId: number[], componentsWithoutParams: IComponent[], sendPortaPrecedente: boolean): Observable<any> {
const url = this.taskUrl + `?serviceId=${serviceIdSi}` + `&actionId=${actionIdSi}` + `&actionClassName=${actionClassName}`
+ `&componentName=${componentName}` + `&taskName=${taskName}`;
if(taskName == "rollBackSPN"){
if(sendPortaPrecedente && componentsWithoutParams.length == 0){
return this.http.post<any>(url, componentsId);
}else{
let errMessage = "Some Error Message"
for(const component of componentsWithoutParams){
errMessage = errMessage + component.idComponent +"\n";
}
throw throwError(errMessage);
}
}else{
return this.http.post<any>(url, componentsId);
}
}
Both these methods are defined in a service called TaskService.
And the service is called like this in a component UnitTaskButtonsComponent.
async launchUnitTask() {
this.isLoading = true;
this.isClosed = false;
this.appComponent.currentComponentIndex = this.componentIndex;
let res = await this.taskService.getComponentIds(this.unitTaskLabel, this.selectedComponents);
this.taskService.executeTask(this.appComponent.currentService.identifiantSi,
this.appComponent.currentAction.identifiantSi,
this.appComponent.currentAction.className,
this.selectedComponents[0].name,
this.unitTaskLabel,
res.componentsId,
res.componentsWithoutParams,
res.sendPortaPrecedente).subscribe(
data => this.executeTaskSuccess(),
error => this.executeTaskError());
}
"res" properties are always undefined when it's a rollBackSPN task.
The main issue here is that getComponentIds does not return a Promise. So awaiting does not work. I would suggest to change getComponentIds so that it returns an Observable instead.
getComponentIds(taskName: string, selectedComponents: IComponent[]) {
// ^^^^^^ use string instead of String
return forkJoin(
selectedComponents.map((component) => {
return this.http.get<any>("Url" + component.idComponent).pipe(
map((val) => {
let sendPortaPrecedente = true;
for (const obj of val) {
if (
(obj.name == "z0bpqPrevious" && obj.value == null) ||
(obj.name == "datePortaPrevious" && obj.value == null) ||
(obj.name == "typePortaPrevious" && obj.value == null)
) {
sendPortaPrecedente = false;
}
}
return { component, sendPortaPrecedente }
}),
catchError((err) => of(err))
);
})
).pipe(
map((result) => {
const componentsId: number[] = [];
const componentsWithoutParams: IComponent[] = [];
for (const val of result) {
if (val.sendPortaPrecedente) {
componentsId.push(val.component.idComponent);
} else {
componentsWithoutParams.push(val.component);
}
}
return { componentsId, componentsWithoutParams };
})
);
}
Instead of using concatMap, let's use a forkJoin. The forkJoin allows sending all requests in parallel and returns the result in an array. But we have to pass in an array of Observables. That's why we map over the selectedComponents.
In the lower map, we can now get the complete result of the http calls in the result parameter. Here we do the processing of the data. I was not really sure how to handle the sendPortaPrecedente. You will have to fill that in.
We simply return the whole Observable
async launchUnitTask() {
this.taskService
.getComponentIds(this.unitTaskLabel, this.selectedComponents)
.pipe(
switchMap((res) => {
this.taskService
.executeTask(
this.appComponent.currentService.identifiantSi,
this.appComponent.currentAction.identifiantSi,
this.appComponent.currentAction.className,
this.selectedComponents[0].name,
this.unitTaskLabel,
res.componentsId,
res.componentsWithoutParams,
res.sendPortaPrecedente
)
})
).subscribe(
(data) => this.executeTaskSuccess(),
(error) => this.executeTaskError()
);
}
In the launchUnitTask method, we don't use await anymore. Instead, we call getComponentIds and chain the call of executeTask with a switchMap.
Configured my store this way with redux toolkit for sure
const rootReducer = combineReducers({
someReducer,
systemsConfigs
});
const store = return configureStore({
devTools: true,
reducer: rootReducer ,
// middleware: [middleware, logger],
middleware: (getDefaultMiddleware) => getDefaultMiddleware({ thunk: false }).concat(middleware),
});
middleware.run(sagaRoot)
And thats my channel i am connecting to it
export function createSocketChannel(
productId: ProductId,
pair: string,
createSocket = () => new WebSocket('wss://somewebsocket')
) {
return eventChannel<SocketEvent>((emitter) => {
const socket_OrderBook = createSocket();
socket_OrderBook.addEventListener('open', () => {
emitter({
type: 'connection-established',
payload: true,
});
socket_OrderBook.send(
`subscribe-asdqwe`
);
});
socket_OrderBook.addEventListener('message', (event) => {
if (event.data?.includes('bids')) {
emitter({
type: 'message',
payload: JSON.parse(event.data),
});
//
}
});
socket_OrderBook.addEventListener('close', (event: any) => {
emitter(new SocketClosedByServer());
});
return () => {
if (socket_OrderBook.readyState === WebSocket.OPEN) {
socket_OrderBook.send(
`unsubscribe-order-book-${pair}`
);
}
if (socket_OrderBook.readyState === WebSocket.OPEN || socket_OrderBook.readyState === WebSocket.CONNECTING) {
socket_OrderBook.close();
}
};
}, buffers.expanding<SocketEvent>());
}
And here's how my saga connecting handlers looks like
export function* handleConnectingSocket(ctx: SagaContext) {
try {
const productId = yield select((state: State) => state.productId);
const requested_pair = yield select((state: State) => state.requested_pair);
if (ctx.socketChannel === null) {
ctx.socketChannel = yield call(createSocketChannel, productId, requested_pair);
}
//
const message: SocketEvent = yield take(ctx.socketChannel!);
if (message.type !== 'connection-established') {
throw new SocketUnexpectedResponseError();
}
yield put(connectedSocket());
} catch (error: any) {
reportError(error);
yield put(
disconnectedSocket({
reason: SocketStateReasons.BAD_CONNECTION,
})
);
}
}
export function* handleConnectedSocket(ctx: SagaContext) {
try {
while (true) {
if (ctx.socketChannel === null) {
break;
}
const events = yield flush(ctx.socketChannel);
const startedExecutingAt = performance.now();
if (Array.isArray(events)) {
const deltas = events.reduce(
(patch, event) => {
if (event.type === 'message') {
patch.bids.push(...event.payload.data?.bids);
patch.asks.push(...event.payload.data?.asks);
//
}
//
return patch;
},
{ bids: [], asks: [] } as SocketMessage
);
if (deltas.bids.length || deltas.asks.length) {
yield putResolve(receivedDeltas(deltas));
}
}
yield call(delayNextDispatch, startedExecutingAt);
}
} catch (error: any) {
reportError(error);
yield put(
disconnectedSocket({
reason: SocketStateReasons.UNKNOWN,
})
);
}
}
After Debugging I got the following:
The Thing is that when I Provide one Reducer to my store the channel works well and data is fetched where as when providing combinedReducers I am getting
an established connection from my handleConnectingSocket generator function
and an empty event array [] from
const events = yield flush(ctx.socketChannel) written in handleConnectedSocket
Tried to clarify as much as possible
ok so I start refactoring my typescript by changing the types, then saw all the places that break, there was a problem in my sagas.tsx.
Ping me if someone faced such an issue in the future
I have a reactive form and adding a custom async validator to check if the values entered is unique by checking the array of available values. The validator is being invoked, but the validation error 'duplicate' is not getting added to the form field errors and not displaying in the template. Not sure what i am doing wrong here.
component.ts
private registerFormGroup(): void {
this.titleField = new FormControl(
{ value: this.auditTemplate.title, disabled: true },
[Validators.required],
[TemplateNameValidator.createValidator(this.auditTemplateService)]
);
this.templateForm = this.formBuilder.group({
title: this.titleField,
tags: [this.auditTemplate.tags]
});
}
name validator:
export class TemplateNameValidator {
static createValidator(auditTemplateService: AuditTemplateService): AsyncValidatorFn {
console.log("Static factory call");
return (control: AbstractControl): Observable<ValidationErrors | null> => {
if(isEmptyInputValue(control.value)) {
return of(null);
} else {
return control.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap((name: string) =>
auditTemplateService.isNameUnique(name)
.pipe
(
tap(response => console.log('inside switchmap', response)),
map(isUnique => !isUnique ? { 'duplicate' : true } : null),
catchError(() => of(null))
)
)
);
}
};
}
}
function isEmptyInputValue(value: any): boolean {
return value === null || value.length === 0;
}
in the template html, if i try to display the error, it is not displaying anything:
<span>Duplicate: </span>{{templateNameField.errors?.duplicate}}<br>
Thanks
AsyncValidators are used every time the AbstractControl state is changed, so you don't need to use the control.valueChanges observable.
Additionally, the observable you're returning from the validator function should send a complete signal after sending null or an error. If you return a hot observable, then the async validator will not work.
Try replacing control.valueChanges.pipe( with of(control.value).pipe(. Also, if your service method .isNameUnique() doesn't emit a complete signal, add take(1) before your the first tap() operator.
return (control: AbstractControl): Observable<ValidationErrors | null> => {
if (isEmptyInputValue(control.value)) {
return of(null);
} else {
return of(control.value).pipe(
distinctUntilChanged(),
debounceTime(500),
switchMap((name: string) =>
auditTemplateService.isNameUnique(name).pipe(
take(1),
tap((response) => console.log("inside switchmap", response)),
map((isUnique) => (!isUnique ? { duplicate: true } : null)),
catchError(() => of(null))
)
)
);
}
};
I have a working subscription that uses withFilter:
User_Presence_Subscription: {
subscribe: withFilter(
() => pubsub.asyncIterator(USER_PRESENCE_UPDATED_CHANNEL),
(payload, args, context) => {
if (typeof (payload) === 'undefined') {
return false;
}
const localUserId = (typeof(context) == 'undefined' || typeof(context.userId) == 'undefined') ? null : context.userId;
const ids_to_watch = args.ids_to_watch;
const usersWithUpdatedPresence = payload.User_Presence_Subscription;
let result = false;
console.log("User_Presence_Subscription - args == ", args, result);
return result;
}
)
}
I'd like to modify the payload before sending it to the client. I tried adding a resolve function as shown in the docs:
User_Presence_Subscription: {
resolve: (payload, args, context) => {
debugger; <== NEVER ACTIVATES
return {
User_Presence_Subscription: payload,
};
},
subscribe: withFilter(
() => pubsub.asyncIterator(USER_PRESENCE_UPDATED_CHANNEL),
(payload, args, context) => {
if (typeof (payload) === 'undefined') {
return false;
}
const localUserId = (typeof(context) == 'undefined' || typeof(context.userId) == 'undefined') ? null : context.userId;
const ids_to_watch = args.ids_to_watch;
const usersWithUpdatedPresence = payload.User_Presence_Subscription;
let result = false;
console.log("User_Presence_Subscription - args == ", args, result);
return result;
}
)
}
...but the debugger line in the resolve function never gets hit.
What's the correct syntax to use here?
Solved. The only reason the resolver wasn't being hit was that in my test code I was returning false from the withFilter function. When it returns true the resolver is hit as expected.
I have problem with my Angular. I have this functions:
private callUserInfo(): any {
this.isLoading = true;
return this._ajaxService.getService('/system/ping')
.map(
result => {
this.userId =
result.participant.substring(result.participant.indexOf('#'));
this.isLoading = false;
}
)
.catch(error => {
return Observable.throw(error);
});
}
public loadUserData(userName: string): any {
this.isLoading = true;
return this._ajaxService.getService('/User/' + userName)
.map(
result => {
const data = result[0];
this.user = new User(
data.id,
data.contacts[0].email,
data.name,
data.surname,
data.address.street,
data.address.city,
data.address.state,
data.address.country,
data.address.postCode,
data.address.timeZone);
this.isLoading = false;
})
.catch(error => {
return Observable.throw(error);
});
}
public getUser(): any {
if (this.user == null) {
this.callUserInfo().subscribe(() => {
this.loadUserData(this.userId).subscribe(() => {
return this.user;
});
});
} else {
return this.user;
}
}
In my component I call this service functions like this (auth service is service with functions defined up):
constructor(private _auth: AuthService) {
this.user = _auth.getUser();
}
But it stills return null (because Ajax calls are not finished?) Can someone explain me, how to call this two calls (first is system/ping service and based on return (userId) I need to call second ajax call (/user/id). After this two calls I have defined user in my service and I can return it to other components. Can someone expllain me, what am i doing wrong, or how I can do it better? I´m using newest version of angular.
P.S. Get service is from my wrapper service:
getService(url: string): Observable<any> {
return this.http
.get(this.base + url, this.options)
.map(this.extractData)
.catch(this.handleError);
}
You are not returning anything in case this.user==null
Change your function as following:
userObservabel=new BehaviourSubject(null);
public getUser(): any {
if (this.user == null) {
this.callUserInfo().subscribe(() => {
this.loadUserData(this.userId).subscribe(() => {
this.userObservabel.next(this.user);
});
});
return this.userObservabel.asObservable();
} else {
return this.userObservabel.asObservable();
}
}
and then you need to subscribe it
constructor(private _auth: AuthService) {
_auth.getUser().subscribe(user => this.user = user);
}
You need to call the second service in the subscribe or in the map method i.e. the Observable has returned a promise and that is resolved. Once that is resolved u should call your chained service.
A sample snipped from my POC might help you
this._accountListService.getAccountsFromBE().subscribe(
response => {
this.response = response;
this._accountListService.getAccountSorting().subscribe(
response => {
this.acctSort = response;
if (response.prodCode) {
this._accountListService.getAccountOrder().subscribe(
response => {
this.acctOrder = response;
this.response = this.setAccountOrder(this.response);
this.response.sort(this.myComparator);
this.acctFlag = true;
if (this.prodDesc) {
this.loader = false;
this.accountDetl = this.response[0];
this.accountDetl.entCdeDesc = this.prodDesc[this.accountDetl.entProdCatCde];
}
},
err => console.log(err)
);
}
},
err => console.log(err)
);
},
err => console.log(err)
);