app.module.tsimport {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.tsimport { 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.tsimport {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.tsimport {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.
1 回答
流叠
TA贡献1条经验 获得超0个赞
试试这样
return this.http.get(myUrl).pipe( map((response: Response) => { response.json(); }));
我不明白为什么你的http get返回的Observable类型还能有map方法
添加回答
举报
0/150
提交
取消