使用接口将数据从 Angular(v 5) 发布到 API 的数据库



我正在使用节点应用程序中在angular(v 5(中进行crud操作。我已经成功地在我的视图中获取了数据。但是我对 Angular 的后脚本有问题。

应用程序的文件结构


我的应用程序模块.ts 文件

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule }   from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';  // <-- #1 import module
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './components/login/login.component';
import { RegisterComponent } from './components/register/register.component';
import { HomeComponent } from './components/home/home.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { ProfileComponent } from './components/profile/profile.component';
import { AuthService } from './services/auth.service';
const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  // { path: '/', component: DashboardComponent },
  { path: 'profile', component: ProfileComponent },
  { path: '**', component: HomeComponent }
];
@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    LoginComponent,
    RegisterComponent,
    HomeComponent,
    DashboardComponent,
    ProfileComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的身份验证文件。

export interface Auth {
    name : string
}

我的身份验证服务.ts 文件

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Auth } from './auth';
import { Observable } from 'rxjs/Observable';
@Injectable()


export class AuthService {
  constructor(private http: HttpClient) { }
  // dataUrl = 'https://jsonplaceholder.typicode.com/posts';
  dataGet = 'http://localhost:3000/user/get';
  dataPost = 'http://localhost:3000/user/post';
  getData(): Observable<Auth[]> {
    return this.http.get<Auth[]>(this.dataGet);
  }
  postData(): Observable<Auth[]> {
    return this.http.post<Auth[]>(this.dataPost,{headers: Headers});
  }
}

我的注册组件.TS 文件

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Auth } from '../../services/auth';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  public auths = [];

  model = {
    name: ""
  }
  constructor(private _authService : AuthService) { }
  ngOnInit() {
    this._authService.postData()
    .subscribe(data => this.auths = data );
  }
}

我的注册组件.html文件

<form (ngSubmit)="(onSubmit)">
    <div class="form-group">
        <label for="exampleInputName1">Name address</label>
        <input type="text" [(ngModel)]="name" name="name" class="form-control" id="exampleInputName1" aria-describedby="NameHelp" placeholder="Enter Name">
      </div>
  <button type="submit" class="btn btn-primary">Submit</button>
  <!-- <input type="submit" class="btn btn-primary" value="Submit"> -->
</form

您应该像这样更新AuthService.postData()方法:

postData(data): Observable<Auth[]> {
  return this.http.post<Auth[]>(this.dataPost, data, {headers: Headers});
}

register.component.html文件中,添加提交处理程序:

<form (ngSubmit)="(onSubmit)">
    <div class="form-group">
        <label for="exampleInputName1">Name address</label>
        <input type="text" [(ngModel)]="model.name" name="name" class="form-control" id="exampleInputName1" aria-describedby="NameHelp" placeholder="Enter Name">
      </div>
  <button type="submit" class="btn btn-primary" (click)="submit()">Submit</button>
</form>

请注意,我已经编辑了[(ngModel)]="model.name"

然后,更新register.component.ts文件,如下所示:

@Component({...})
export class RegisterComponent implements OnInit {
  public auths = [];
  model = {
    name: ""
  }
  constructor(private _authService : AuthService) { }
  ngOnInit() {
    // remove the logic here
  }
  // add this method - I moved the logic you wrote inside the ngOnInit method here
  submit() {
    this._authService.postData(this.model)
    .subscribe(data => this.auths = data );
  }
}

希望对您有所帮助! :)

in your service auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Auth } from './auth';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthService {
  constructor(private http: HttpClient) { }
  // dataUrl = 'https://jsonplaceholder.typicode.com/posts';
  dataGet = 'http://localhost:3000/user/get';
  dataPost = 'http://localhost:3000/user/post';
  getData(): Observable<Auth[]> {
    return this.http.get<Auth[]>(this.dataGet);
  }
  postData(data){
    let headers = new HttpHeaders();
    headers.append('X-Requested-With', 'XMLHttpRequest');
    headers.append('Content-Type' : 'application/json'); 
    return this.http.post(this.dataPost,data,{headers: headers });
  }
}

在您的组件注册中。

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Auth } from '../../services/auth';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
   auths:any = [];

    name:string ="";

  constructor(private _authService : AuthService) { }
  ngOnInit() {
  }
 onSend(){
    this._authService.postData({name: this.name})
    .subscribe(data => this.auths = data );
  }
}

注册组件.html

<form>
    <div class="form-group">
        <label for="exampleInputName1">Name address</label>
        <input type="text" [(ngModel)]="name" name="name" class="form-control" id="exampleInputName1" aria-describedby="NameHelp" placeholder="Enter Name">
      </div>
  <button type="button" class="btn btn-primary" (click)="onSend()">Submit</button>
  <!-- <input type="submit" class="btn btn-primary" value="Submit"> -->
</form

相关内容

  • 没有找到相关文章

最新更新