你不應該導入整個包作爲
import * as AWSCognito from 'amazon-cognito-identity-js';
這是個壞主意,因爲你不需要一堆膨脹的它。
取而代之,只導入你需要的東西。看我下面的例子。
import {AuthenticationDetails, CognitoUser, CognitoUserAttribute, CognitoUserPool} from 'amazon-cognito-identity-js';
const PoolData = {
UserPoolId: 'us-east-1-xxxxx',
ClientId: 'xxxxxxxxxxx'
};
const userPool = new CognitoUserPool(PoolData);
/////in export class....
/// Sign Up User
signupUser(user: string, password: string, email: string) {
const dataEmail = {
Name: 'email',
Value: email
};
const emailAtt = [new CognitoUserAttribute(dataEmail)];
userPool.signUp(user, password, emailAtt, null, ((err, result) => {
if (err) {
console.log('There was an error ', err);
} else {
console.log('You have successfully signed up, please confirm your email ')
}
}))
}
/// Confirm User
confirmUser(username: string, code: string) {
const userData = {
Username: username,
Pool: userPool
};
const cognitoUser = new CognitoUser(userData);
cognitoUser.confirmRegistration(code, true, (err, result) => {
if (err) {
console.log('There was an error -> ', err)
} else {
console.log('You have been confirmed ')
}
})
}
//// Sign in User
signinUser(username: string, password: string) {
const authData = {
Username: username,
Password: password
};
const authDetails = new AuthenticationDetails(authData);
const userData = {
Username: username,
Pool: userPool
};
const cognitoUser = new CognitoUser(userData);
cognitoUser.authenticateUser(authDetails, {
onSuccess: (result) => {
// console.log('You are now Logged in');
this.isUser.next(true);
this.router.navigate(['/'])
},
onFailure: (err) => {
console.log('There was an error during login, please try again -> ', err)
}
})
}
/// Log User Out
logoutUser() {
userPool.getCurrentUser().signOut();
this.router.navigate(['home'])
}
創建'CognitoIdentityServiceProvider'的實例 – Aravind