Angular Http Observable不会更新

时间:2017-11-18 12:12:37

标签: javascript angular typescript rxjs

Hey Guys我写了一个小后端,它返回了一些数据。现在我想用Angular Http获取这些数据,并在我在后端发布它们时显示新值。所以我想到的第一件事是Observables,但目前我可以获取数据onInit,但是当将新数据发布到后端(目前只是通过Postman)时,Fetched数据不会更新。所以,如果这是错误的方法请告诉我如何做到这一点。以下是我目前使用的代码:

应用组件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import {WeaponServiceService} from './weapon-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  weaponTypesarr: IweaponsTypes [] = [
    {name: 'Nahkampf', value: 'melee'},
    {name: 'Fernkampf', value: 'ranged'},
    {name: 'Spezial', value: 'special'},
  ];
  meleeTypesarr: IweaponsTypes [] = [
    {name: 'Klingenwaffen', value: 'klinge'},
    {name: 'Messer', value: 'messer'},
    {name: 'Dolche', value: 'dolch'},
    {name: 'Äxte/Beile', value: 'axt'},
    {name: 'Speere/Stäbe', value: 'speer'},
    {name: 'Stumpfe Hiebwaffen', value: 'stumpf'}
  ];
  rangedTypesarr: IweaponsTypes [] = [
    {name: 'Bogen', value: 'bogen'},
    {name: 'Armbrust', value: 'armbrust'},
    {name: 'Wurfwaffe', value: 'wurfwaffe'},
    {name: 'kleine Schusswaffe', value: 'gun-litte'},
    {name: 'große Schusswaffe', value: 'gun-big'}
  ];
  specialTypesarr: IweaponsTypes [] = [
    {name: 'Exotische Waffen', value: 'exotics'},
    {name: 'Granaten und Exoplosive', value: 'grenade'}
  ];
  rForm: FormGroup;
  post: any;
  weaponName = '';
  weaponType= '';
  impairment= '';
  special= '';
  results: Observable<any>;
  constructor(private fb: FormBuilder , private weaponService: WeaponServiceService) {
    this.rForm = fb.group({
      'weaponName' : [null, Validators.required],
      'weaponType': [null, Validators.required],
      'impairment': [null, Validators.required],
      'special': [null, Validators.required]
    });
  }
  ngOnInit() {
     this.results = this.weaponService.getWeapons();
     this.results.subscribe(data => {console.log(data); });
  }

  generateWeapon(weaponData) {
    this.weaponName = weaponData.weaponName;
    this.weaponType = weaponData.weaponType;
    this.impairment = weaponData.impairment;
    this.special = weaponData.special;
    console.log(weaponData);
  }

}


export interface IweaponsTypes {
  name: string;
  value: string;
}

WeaponServiceService(不知道它自己称之为服务:D):

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class WeaponServiceService {

  constructor( private http: HttpClient) { }

  getWeapons() {
    return this.http.get('http://192.168.178.48:3000/getWeapons').map(data => {
      return(data);
    },
    err => {
      console.log(err);
    }
  );
  }

  createWeapon(weaponData2: any) {
    return this.http.post('http://192.168.178.48:3000/createWeapon', weaponData2)
    .map(
      res => {
        console.log(res);
      },
      err => {
        console.log(err);
      }
    );
  }
}

模块:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import {WeaponServiceService} from './weapon-service.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
    NgbModule.forRoot()
  ],
  providers: [WeaponServiceService],
  bootstrap: [AppComponent]
})
export class AppModule { }

最后但并非最不重要的是相应的HTML,但目前我只是尝试记录所有值。

<div *ngIf="!name; else forminfo">
  <form [formGroup]="rForm" (ngSubmit)="generateWeapon(rForm.value)">
        <h1>Generate Weapon</h1>
        <label for="WeaponName">WeaponName</label>
        <input  class="form-control" type="text" name="weaponName" formControlName="weaponName" id="WeaponName">
        <div class="form-group">
            <label for="WeaponGroup">Weapon Group</label>
                <select class="form-control" #weaponTypeSelektor formControlName="weaponType" id="WeaponGroup">
                    <option> Select a Type</option>
                    <option *ngFor="let types of weaponTypesarr" [value]="types.value">{{types.name}}</option>
                </select>
          </div>
          <div class="form-group" *ngIf="weaponTypeSelektor.value == 'melee'">
              <label for="WeaponTypeMelee">Weapon Type</label>
                  <select class="form-control" formControlName="weaponType" id="WeaponTypeMelee">
                      <option *ngFor="let types of meleeTypesarr" [value]="types.value">{{types.name}}</option>
                  </select>
            </div>
            <div class="form-group" *ngIf="weaponTypeSelektor.value == 'ranged'">
                <label for="WeaponTypeRanged">Weapon Type</label>
                    <select class="form-control" formControlName="weaponType" id="WeaponTypeRanged">
                        <option *ngFor="let types of rangedTypesarr" [value]="types.value">{{types.name}}</option>
                    </select>
              </div>
              <div class="form-group" *ngIf="weaponTypeSelektor.value == 'special'">
                  <label for="WeaponTypeSpecial">Weapon Type</label>
                      <select class="form-control" formControlName="weaponType" id="WeaponTypeSpecial">
                          <option *ngFor="let types of specialTypesarr" [value]="types.value">{{types.name}}</option>
                      </select>
                </div>
        <label for="impairment">Beeinträchtigung</label>
        <input class="form-control" type="text" name="Beeinträchtigung" formControlName="impairment" value="" id="impairment">
        <label for="special">Spezial</label>
        <input class="form-control" type="text" name="Spezial" formControlName="special" value="" id="special">
        <br><br>
        <input type="submit" class="btn btn-primary" value="Submit Form" [disabled]="!rForm.valid">
  </form>

  <div  *ngFor="let item of results | async"> {{item.weaponName}} </div>
</div>

<ng-template #forminfo>
  <div class="form-container">
    <div class="row columns">
        <h1>{{ name }}</h1>

        <p>{{ weaponType }}</p>
    </div>
  </div>
</ng-template>

所以要清楚。 AppComponent启动并获取初始数据。我用邮递员将数据发布到Db中。 App Component无法识别新值。

1 个答案:

答案 0 :(得分:0)

更改服务中的这些行。

getWeapons() {
return this.http.get('http://192.168.178.48:3000/getWeapons').map(data => {
  return data.json();
}

并在AppComponent中更改这些行

ngOnInit() {
 this.results = this.weaponService.getWeapons();
 //delete this line ---> this.results.subscribe(data => {console.log(data); });
}

因为您使用的是异步管道,所以您无需订阅。 希望这会有所帮助。