zoukankan      html  css  js  c++  java
  • angular2 问题请教

    angular2 通过http服务进行对后端api的远程调用?

    我简单的尝试了一下,发现了几个问题,记录一下,以方便查找问题。

    1. angular2 http服务的跨域问题?跨域本身就是一个很复杂的问题,angular2对跨域的处理。
    2. angular2 如果在providers中加入http服务会出现什么问题?
    3. promise http服务会强迫我们使用Observerable,但是我们可以转换成promise,还是遵循官方指导,学习rxjs吧。

    现在我们先看第二个问题?

     1 import { NgModule } from '@angular/core';
     2 import { Http, HttpModule } from '@angular/http';
     3 import { HeroListComponent } from './hero-list.component';
     4 
     5 @NgModule({
     6     imports: [HttpModule],
     7     declarations: [HeroListComponent],
     8     providers: [Http]
     9 })
    10 
    11 export class HeroListModule
    12 { }

    我在providers中添加了http服务。如果此时我通过http获取远程url内容。

     1 import { Component } from '@angular/core';
     2 import { Http } from '@angular/http';
     3 
     4 @Component({
     5     templateUrl: './hero-list.component.html'
     6 })
     7 
     8 export class HeroListComponent {
     9     private baiduhtml: string;
    10     constructor(private http: Http) {
    11         this.http.get("http://localhost:8080/dashboard/datalist").toPromise().then((data) => {
    12             this.baiduhtml = data.text();
    13         }).catch(this.handleError);
    14     }
    15 
    16     private handleError(error: any): Promise<any> {
    17         console.error('An error occurred', error); // for demo purposes only
    18         return Promise.reject(error.message || error);
    19     }
    20 
    21 }

    很不好意思?出现了错误

    如果我们去掉providers中的http,执行正常。

    这是不是提示我们,服务不能重复的在providers中添加呢?那么如果不能重复添加,我们该如何避免呢?暂时没想到好办法,希望有合适方法的指导一下??

     因为团队开发,我们不能避免出现重复添加的问题。

    关于跨域问题的研究,加入一个header就可以搞定,这涉及到了http的细节,不属于问题。

  • 相关阅读:
    改善用户体验之alert提示效果
    用javascript制作放大镜放大图片
    window.history.go(1)返回上页的同时刷新"上页"技术
    JS折叠菜单
    懒得勤快的博客 resharper 等好文
    IBM DOMINO LOTUS LIMITS
    为CKEditor开发FLV视频播放插件
    Calling DLL routines from LotusScript. Part I: Windows API
    lotus domino下使用FCKeditor
    domino文件拆离数据库,放入指定目录
  • 原文地址:https://www.cnblogs.com/jiagoushi/p/6115954.html
Copyright © 2011-2022 走看看