我是Angular的新手,
尝试创建将从MongoDB数据库中获取记录的函数,但是出现问题。 API URL工作正常。
文件:data.services.spec.ts
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
@Injectable()
export class DataService {
result:any;
constructor(private _http: Http) { }
getUsers() {
return this._http.get("/api/users")
.map(result => this.result = result.json().data);
}
}
文件:app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// Import the Http Module and our Data Service
import { HttpModule } from '@angular/http';
import { DataService } from './data.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule
],
providers: [ DataService ],
bootstrap: [AppComponent]
})
export class AppModule { }
文件:app.component.ts
import { Component } from '@angular/core';
// Import the DataService
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'mean';
// Define a users property to hold our user data
users: Array<any>;
// Create an instance of the DataService through dependency injection
constructor(private _dataService: DataService) {
// Access the Data Service's getUsers() method we defined
this._dataService.getUsers()
.subscribe(res => this.users = res);
}
}
错误在这里this._dataService.getUsers()
。
任何建议将不胜感激。
答案 0 :(得分:2)
您应该在 data.services.ts 中写服务,而不要在 data.services.spec.ts
中写服务在data.services.ts
import { Injectable } from '@angular/core';
import { Observable} from 'rxjs';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
@Injectable()
export class DataService {
result:any;
constructor(private _http: Http) { }
getUsers(): Observable<any> {
return this._http.get("/api/users")
.map(result => this.result = result.json().data);
}
}
在组件中:
import { DataService } from './data.service';
答案 1 :(得分:1)