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(){
?????????//向服務(wù)器發(fā)請求
?????????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對應(yīng)的服務(wù)器端發(fā)送請求
????sendRequest(myUrl:string){
????????return?this.http.get(myUrl)
????????????.map((response:?Response)?=>?{
????????????????response.json();
????????})
????}
}請問下,為何拿不到返回結(jié)果, 控制臺輸出結(jié)果是undefined.
angular2.0封裝http請求服務(wù),拿不到返回結(jié)果?
天天向上學(xué)
2019-09-23 16:22:13