22 July 2019
Angular (37) -- NgRx Effects
by Jerry Zhang
LeetCode Day 17: P136. Single Number (Easy)
题目:
一个整数的数组,所有数都是成对出现的,只有一个落单。找出这个落单的数。
Example 2:
Input: [4,1,2,1,2] Output: 4
我的思路:
用HashSet可以,但是成本太高。题目要求时间复杂度O(n), 并且不用额外的空间。所以也不可能每次都往前找一遍。放弃了,看答案。
最优解:
class Solution {
public int singleNumber(int[] nums) {
for(int i = 0; i < nums.length - 1; i++){
nums[i+1] ^= nums[i];
}
return nums[nums.length-1];
}
}
用XOR位运算,重复的都会被自动消掉。所以以后凡是遇到解决配对的问题,首先想想能否用XOR
Angular
Set navigation as a side effect
In the auth.effects.ts
file, add a new effect.
@Effect({dispatch: false})
authRedirect = this.actions$.pipe(
ofType(AuthActions.AUTHENTICATE_SUCCESS),
tap(() => {
this.router.navigate(['/']);
})
);
This is an effect which does not dispatch a new action. It does not return a new observable. So we set the dispatch to false.
Display the error message
In the auth.component.ts
file:
ngOnInit(): void {
this.storeSub = this.store.select('auth').subscribe(authState => {
this.isLoading = authState.loading;
this.error = authState.authError;
if (this.error) {
this.showErrorAlert(this.error);
}
});
}
In the auth.effects.ts
file, we need to return our action.
const handleError = (errorRes: any) => {
let errorMessage = 'An unknown error occured!';
if (!errorRes.error || !errorRes.error.error) {
return of(new AuthActions.AuthenticateFail(errorMessage));
}
switch (errorRes.error.error.message) {
case 'EMAIL_EXISTS':
errorMessage = 'This email exists already';
break;
case 'EMAIL_NOT_FOUND':
errorMessage = 'This email does not exist';
break;
case 'INVALID_PASSWORD':
errorMessage = 'This password is not correct.';
break;
}
return of(new AuthActions.AuthenticateFail(errorMessage));
};
catchError(errorRes => {
return handleError(errorRes);
})