HttpClientModule返回空数组

时间:2018-11-14 18:04:06

标签: javascript angular

我想使用HttpClientModule来访问Post的Array。 我只是在学习Angular,所以有人可以向我解释为什么这是错误的

  

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { HatedPostListComponent } from './hated-post-list/hated-post-list.component';
import { HatedAboutUsComponent } from './hated-about-us/hated-about-us.component';
import { HatedLoginComponent } from './hated-login/hated-login.component';
import { DataService } from './services/data.service';

@NgModule({
  declarations: [
    AppComponent,
    HatedPostListComponent,
    HatedAboutUsComponent,
    HatedLoginComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }
  

app.component.ts

import { Component } from '@angular/core';
import { DataService } from './services/data.service';
import { Post } from './models/user.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Frontend';
  constructor (private _svc: DataService) {
    console.log('Data in component' + this._svc.data);
  }
  getDate(): Array<Post> {
    return this._svc.data;
  }
}
  

data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Post } from '../models/user.model';

@Injectable()
export class DataService {
  baseURL: string;
  data: Array<Post> = [];
  constructor(private _http: HttpClient) {
    this.baseURL = 'http://localhost:5000/Posts?from=0&number=10';

  }
  getDate() {
    this._http.get<Array<Post>>(this.baseURL)
    .subscribe(response => {
      this.data = response;
      console.log('Subcribed data:' + this.data);
      console.log('Subcribed response:' + response);
    }
  );
  console.log('Data after subcribe:' + this.data);
  }
}

这就是我的意思 result 当我订阅()时一切正常,但是之后我的数据为空

2 个答案:

答案 0 :(得分:-1)

您需要调用该服务并订阅您不在该服务中的组件。

将您的服务代码更改为

getDate() {
   return this._http.get<Array<Post>>(this.baseURL);
}

以及您组件中的

 getDate(): Array<Post> {
    this._svc.getDate().subscribe(
      res => {
        console.log(res);       
      },
      err => console.log(err)
    );
  }

答案 1 :(得分:-1)

将实现更改为遵循以下操作即可获得预期结果。

您的组件:

getDate(){
  this._svc.getDate().subscribe((res)=> {
    console.log(res)
  });
}

您的服务:

getDate() {
  return this._http.get(this.baseURL);
}

这应该有效。逻辑问题是您只是在监听服务中数据的当前值。如果该时间点服务保留[],则从API接收数据后,除非您订阅该更改,否则不会通知您组件更改。