Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Submit form.value to signIn method #28

Closed
artem-galas opened this issue Sep 22, 2016 · 9 comments
Closed

Submit form.value to signIn method #28

artem-galas opened this issue Sep 22, 2016 · 9 comments

Comments

@artem-galas
Copy link

For example, we use the form as FormGroup for SignIn. Then we have incorrect data gets to BackEnd.
For example we have SignIn form, it contains the next object -

{
  email:"[email protected]"
  password:"123456789"
}

And when sending to RailsApp, we get such parameters -

Parameters: {"email"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}, 
"session"=>{"email"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}}

I think should overwrite signIn/signUp methods such way, so that they can pass form.value method.
What do you think about it?

Example signIn.component.ts (code such similar with article about FormValidataion

import { Component OnInit} from '@angular/core';
import {Router} from '@angular/router';
import { Angular2TokenService } from 'angular2-token';
import { AuthData } from '../shared/auth/auth';
import {FormBuilder, Validators, FormGroup} from '@angular/forms';

@Component({
  moduleId: module.id,
  selector: 'sign-in',
  templateUrl: 'sign-in.component.html'
})
export class SignInComponent implements OnInit{
  signInForm: FormGroup;
  formErrors = {
    'email': '',
    'password': ''
  };

  validationMessages = {
    'email': {
      'required': 'Name is required'
    },
    'password': {
      'required': 'Password is required'
    }
  };
  private errors: string[];

  constructor(private _tokenService: Angular2TokenService,
              private router: Router,
              private fb: FormBuilder) { }

  ngOnInit(): void {
    this.buildForm();
  }

  buildForm(): void {
   this.signInForm = this.fb.group({
     'email': [this._authData.email,[
       Validators.required
      ]
     ],
     'password': [this._authData.password]
   });
    this.signInForm.valueChanges
      .subscribe(data => this.onValueChanged(data));
    this.onValueChanged();
  }

  onValueChanged(data?:any) {
    if (!this.signInForm) {return;}
    const form = this.signInForm;

    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  // Submit Data to Backend
  onSubmit() {
    this._tokenService.signIn(
      this.signInForm.value
    ).subscribe( res => this.router.navigate(['/']),
                 err => this.errors = err.json().errors);
  }

Example signIn.component.html

<h2>Sign in</h2>
    <form class="ui form" id="new_user" (ngSubmit)="onSubmit()" [formGroup]="signInForm">
    <div class="field">
      <input placeholder="username" autofocus="autofocus"  type="text" formControlName="email" required>
    </div>

    <div class="field">
      <input placeholder="password" autocomplete="off"  type="password" formControlName="password" required>
    </div>

    <div class="actions field">
      <button [disabled]="!signInForm.valid" type="submit" class="ui primary button large fluid">Sign In</button>
    </div>
  </form>
@neroniaky
Copy link
Owner

Hey @artem-galas, I finally got around to take a deeper look at this behavior.

this.signInForm.value seems to return a hash, so the .signIn() etc. need to be modified to accepts a hash like

signIn({email: string, password: string})

instead of

signIn(email: string, password: string)

I'm not 100% sure how to modify this without breaking every existing implementation, because (as far as I know) there is no method overloading in Typescript.

Anyways, the behavior you described

Parameters: {"email"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}, 
"session"=>{"email"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}}

seems to be Rails related. Angular2-Token sends only a hash like {email: string, password: string} in the body of the Post-Request. I don't know yet what is causing this.

@rafaelss95
Copy link

rafaelss95 commented Oct 22, 2016

Any news on this? I'm facing the same problem.
I got the same behavior described above even testing with the sample on README.md.

@neroniaky
Copy link
Owner

@rafaelss95 did a little research on this, but couldn't find a solution yet. Seems to be a problem with rails and angular2. Would be nice if someone could confirm this.
For me this doesn't cause any problems in normal use, but something that needs to be solved anyways.

@rafaelss95
Copy link

rafaelss95 commented Oct 23, 2016

@neroniaky, well, as a suggestion I think would be better if we could pass the whole object to the functions. And about a possible problem with Rails and Angular2, I have some services implemented and I don't got any kind of error (I usually do the following):

Component:

this.userService.login({'user': this.form.value})

Service:

login(body: {}): Observable<Response> {
  const bodyString = JSON.stringify(body);
  const headers = new Headers({ 'Content-Type': 'application/json' });
  const options = new RequestOptions({ headers: headers });
  return this.http.post(this.apiUrl, body, options);
}

So, I get the following code, which works perfectly:

Processing by Devise::SessionsController#create as JSON
  Parameters: {"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}}

@neroniaky
Copy link
Owner

@rafaelss95 Thank you for your input. I'm working on version 0.2.0 which is supposed to support passing the entire object. Hope to publish it soon.

@rafaelss95
Copy link

Hello, @neroniaky, any news on this?

@neroniaky
Copy link
Owner

Hey @rafaelss95, I had quite a lot to do in the last weeks. Version 0.2.0 is almost done. I hope to publish a beta this week.

@kamrantgp
Copy link

@neroniaky hey how is it going with the fix?

@rafaelss95 Could you provide more details on ur hack?

@neroniaky
Copy link
Owner

@kamrantgp @rafaelss95 I just published v0.2.0-beta.1. Would be good if you could give it try 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants