How to save returned value from a server

耗尽温柔 提交于 2020-01-15 09:52:09

问题


I have the following web service that is hosted online and validates wheter or not we can add a new user into our system.

router.post('/register', (req, res) => {  
var user = req.body;   

var userPromise = new Promise(async (resolve, reject) => {
    resolve(await findBy("Users", "email", user.email.toLowerCase()));
})
.then(function(result){
    if (result){
        res.status(418).end(JSON.stringify("User already exists."));
        return;
    }

    var pass;
    var passPromise = new Promise(async (resolve, reject) => {
        resolve(await bcrypt.hashSync(user.password));
    })
    .then(function(result){
        var createPromise = new Promise(async (resolve, reject) => {
            try{
                await createUser(user.name, user.email.toLowerCase(), result); 
                resolve();
            }
            catch (err){
                reject();
            }            
        })
        .then(function(result){
            res.status(200).end(JSON.stringify("Signup successful."));
        })
        .catch(function(result){
            res.status(418).end(JSON.stringify("Failed to create user."));
        });
    }); 
});
});

For some extra detail here is the methods called inside this function.

function createUser (userName, userEmail, userPass, dev) {
var mg = require('mongodb').MongoClient;

mg.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, db){
    var dbo = db.db(myDB);
    var user = { name: userName, 
                 email: userEmail,
                 password: userPass,
                 devices: dev };

    var insert = util.promisify(dbo.collection("Users").insertOne);

    dbo.collection("Users").insertOne(user, function(err, res) {
        if (err) 
            throw err;

        console.log(`${user.name} has been added.`);
        db.close();

        sendEmail(userEmail, 
                  'The CRUST Company welcomes you!',
                  'Thank you for signing up for our services!' );
    });
});
}

 //See if a user exists
async function findBy (collection, queryField, value) {
var mg = require('mongodb').MongoClient;

return new Promise(function(resolve, reject) {
    mg.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, db) {
      if (err) 
        reject(err);  
      else 
        resolve(db);   
    });
})
.then((result) => {
    db = result;
    var dbo = db.db(myDB);
    var query = { };
    query[queryField] = value;

    var val = dbo.collection(collection).findOne(query);
    db.close();
    return(val);
})
.catch();
}

Now within my main application I want to be able to call my method register that passes the needed information through to the web service for validation and if the user is accepted i must navigate to the login form and if the system returns an error I want to be able to display that error. Here is the code i currently have.

 register(postData: User): Observable<AuthResponse> {
 try {
    this.http.post<AuthResponse>(`https://1146c1fe.ngrok.io/register`, (postData)).pipe(
    tap(async (res: AuthResponse ) => {
      console.log('I am done.');
    })
  );
 } catch (err) {
   alert('Error.Error');
   console.log('Error.Error');
 }
 return;
}

I am unsure on what must be within the AuthResoponse class at this stage so any advice there would help and also if the user is accepted then the 'I am done' is printed in the console but if the server says no then then no message is displayed in the console.

So a brief recap i simply want to be able to catch and display the error messages to the user and then keep them on this page.


回答1:


Since you are using Ionic 4, you should use services to direct the HTTP requests. Inside this service, you should handle your incoming data or incoming error and pass them back to your page. The function in auth.service is an Observable, so you can subscribe to it to receive the result or the error.

register.page.ts
Register function in the .ts file which points to the AuthService and uses a function provided in the service to make the request and receive a response or an error

constructor(
  private authService: AuthService,
  // other stuff
) {}

register() {
  this.authService
    .register(data) // execute register function in auth.service
    .subscribe(
      result => { // your result from observer.next() in auth.service
        // success
      },
      error => { // your error from observer.error() in auth.service
        // no success
      }
    );
}

auth.service.ts
Make the http post call and receive data or errors from your webservice and pass them to your register() function in page.ts

register(data): Observable<any> {
  return new Observable(observer => {
    this.http.post(URL, data)
      .pipe(
        catchError(error => {
          return throwError(error); // if you catch any errors, pass them (rethrow) to the error block
        })
       )
       .subscribe(
         result => {
           observer.next(result); // if you receive a result, pass to register function in register.page.ts
           observer.complete(); // close the observable
         },
         error => {
           observer.error(error); // if you receive an error, pass error to register function
           observer.complete(); // close the observable
          }
        );
      });
}


来源:https://stackoverflow.com/questions/57875969/how-to-save-returned-value-from-a-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!