app.module.ts
import {HttpModule}from '@angular/http'; import {Demo26Component} from './demo26_http/demo26.component'; import {MyHttpService} from './demo26_http/myhttp.service'; @NgModule({ imports: [HttpModule,BrowserModule, FormsModule, AppRoutingModule], declarations: [Demo26Component], bootstrap: [AppComponent], providers:[MyHttpService] }) export class AppModule { }
app.router.ts
import { Demo26Component } from './demo26_http/demo26.component'; const routes: Routes = [ { path: '', redirectTo: '/demo26', pathMatch: 'full' }, { path: 'demo26', component: Demo26Component },\ ] @NgModule({ i mports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
demo26.component.ts
import {Component,OnInit} from '@angular/core'; import{MyHttpService} from './myhttp.service'; @Component({ selector:'demo26', template:` <h2>demo26,封装http请求的封装<h2> <button (click)="handleClick()">加载更多</button> ` }) export class Demo26Component implements OnInit{ //myList:Array<any>=[]; myList:any[]=[]; constructor(private myService:MyHttpService){} ngOnInit(){} handleClick(){ //向服务器发请求 console.log(1111); this.myService.sendRequest('http://jsonplaceholder.typicode.com/users').subscribe((result:any)=>{ console.log(result); }) } }
myhttp.service.ts
import {Injectable}from '@angular/core'; import {Http,Response} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class MyHttpService{ constructor(private http:Http){} //定义了一个方法是向myUrl对应的服务器端发送请求 sendRequest(myUrl:string){ return this.http.get(myUrl) .map((response: Response) => { response.json(); }) } }
请问下,为何拿不到返回结果, 控制台输出结果是undefined.
流叠
相关分类