使用angularjs2和验证开发登录页面

时间:2016-11-29 10:10:33

标签: html5 angular


我是angularjs2的新手。
我已经使用angularjs2和验证准备了登录页面。但是我收到了一些错误。 在这里我有attached我的代码有错误。

查看代码:

<form [formGroup]="loginForm" (ngSubmit)="onSubmit(form.value)" class="smart-form client-form">
 <header>Sign In</header>
   <fieldset>
     <section>
        <label class="label">UserName</label>
        <label class="input">
          <i class="icon-append fa fa-user"></i>
          <input type="text" id="username" [formControl]="form.controls['username']" >
          <control-messages [control]="loginForm.controls.username"></control-messages>
          <b class="tooltip tooltip-top-right">
           <i class="fa fa-user txt-color-teal"></i>
               Please enter username
          </b>
        </label>
     </section>

    <section>
        <label class="label">Password</label>
        <label class="input"> 
         <i class="icon-append fa fa-lock"></i>
         <input type="password" id="password" formControlName="password">
         <control-messages [control]="loginForm.controls.password"></control-messages>
         <b class="tooltip tooltip-top-right">
          <i class="fa fa-lock txt-color-teal"></i>
            Enter your password
         </b> 
       </label>
       <div class="note">
        <a href="forgotpassword">Forgot password?</a>
       </div>
    </section>
 </fieldset>
 <footer>
    <button type="submit" class="btn btn-primary" [disabled]="!loginForm.valid">
     Sign in
    </button>
 </footer>

CONTROLLER:

import { Component } from '@angular/core';
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from '@angular/forms';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import { ValidationService } from 'app/validation.service';

@Component({
  moduleId: module.id,
  selector: 'login-app',
  templateUrl: 'login.html',
  styleUrls: ['login.css'],
  directives: [FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES]
})
export class LoginComponent  
{
    form: FormGroup;
    userForm: any;

    constructor(private formBuilder: FormBuilder) {

    this.loginForm = this.formBuilder.group({
      'username': ['', Validators.required],
      'password': ['', [Validators.required, Validators.minLength(10)]]
    });

    console.log(this.userForm);
   }

  saveData() {
    if (this.loginForm.dirty && this.loginForm.valid) {
      alert(`Username: ${this.loginForm.value.username} Password: ${this.loginForm.value.password}`);
    }
  }

}

NGMODULE:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { AppComponent }  from './app.component';
import { ControlMessagesComponent } from './control-messages.component';
import { ValidationService } from './validation.service';

import { LoginComponent }  from './login/login.component';
import { ProjectgroupsComponent }  from './Projectgroups/projectgroups.component';
import { PageNotFoundComponent }  from './PageNotFound/pagenotfound.component';


/*
const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', component: LoginComponent },
  {path: '/404', name: 'NotFound', component: PageNotFoundComponent},
  {path: '**', redirectTo: 404}
];
*/
export const routeConfig:Routes = [
    { path: 'login', component: LoginComponent },
    {
        path: "**",
        component: PageNotFoundComponent
    },
    {
        path: "",
        component: LoginComponent
    }
];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(routeConfig)
  ],
   exports: [
        FormsModule,
        ReactiveFormsModule
   ],
  declarations: [
    ControlMessagesComponent,
    AppComponent,
    LoginComponent,
    ProjectgroupsComponent,
    PageNotFoundComponent
  ],
  providers: [ ValidationService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
export class AppRoutesModule {}
platformBrowserDynamic().bootstrapModule(AppModule)

我的问题是: 我该如何解决这个错误呢? 有没有其他可能的解决方案来避免这个错误?
所有建议都是可以接受的 感谢所有提前。

1 个答案:

答案 0 :(得分:0)

更改

loginForm: FormGroup; //change here

public class GPSActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private static String TAG = "GPSActivity";

// Required for setting API
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
GoogleApiClient googleApiClient;

private Button mBtnGPS;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gps);

    mBtnGPS = (Button) findViewById(R.id.btnGPS);

    mBtnGPS.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btnGPS:
            // Check GPS
            checkGps();
            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
    if (requestCode == REQUEST_CHECK_SETTINGS) {
        googleApiClient = null;
        checkGps();
    }
}

public void checkGps() {
    if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient.Builder(GPSActivity.this)
                .addApiIfAvailable(LocationServices.API)
                .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
        googleApiClient.connect();

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        builder.setAlwaysShow(true); // this is the key ingredient

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
                .checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result
                        .getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        Log.i("GPS", "SUCCESS");
                        //getFbLogin();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        Log.i("GPS", "RESOLUTION_REQUIRED");
                        // Location settings are not satisfied. But could be
                        // fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling
                            // startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(GPSActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.i("GPS", "SETTINGS_CHANGE_UNAVAILABLE");
                        // Location settings are not satisfied. However, we have
                        // no way to fix the
                        // settings so we won't show the dialog.
                        break;
                    case LocationSettingsStatusCodes.CANCELED:
                        Log.i("GPS", "CANCELED");
                        break;
                }
            }
        });
    }
}

@Override
public void onConnected(Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

它应该有用