2016-07-01 2 views
9

무엇을하려고합니까 :
http 요청이 발생할 때마다 회 전자를 사용하고 싶습니다. 즉, 내 app.component에서 http 요청이 발생할 때마다 사용자가 로딩 화면을 보길 원합니다.
내 spinner.component 및 spinner-service 파일은 this 질문의 답변과 동일합니다. HTTP 요청은이 노선 중 하나가 발생할 때마다
그리고 내 app.component의 구성 요소,각 http 요청에 각도 2 로더

@Component({ 
    selector: 'todoApi', 
    template: ` 
     <div class="foo"> 
      <spinner-component></spinner-component> 
      <h1>Internship Project</h1> 
      <a [routerLink]="['Dashboard']">Dashboard</a> 
      <a [routerLink]="['Tasks']">List</a> 
      <router-outlet></router-outlet> 
     <div> 
    `, 
    directives: [ROUTER_DIRECTIVES,SpinnerComponent], 
    providers: [ 
     ROUTER_PROVIDERS, 
    ] 
}) 

@RouteConfig([ 
    { 
     path: '/dashboard', 
     name: 'Dashboard', 
     component: DashboardComponent, 
     useAsDefault: true 
    },{ 
     path: '/tasks', 
     name: 'Tasks', 
     component: TaskComponent 
    },{ 
     path: '/detail/:id', 
     name: 'TaskDetail', 
     component: TaskDetailComponent 
    }, 
]) 

conclue하는 것입니다, 나는 사용자에게 스피너를 보여주고 싶어요. 나는 이것이 나쁜 질문 이었음을 안다. 그러나 나는 각도 2를 처음 접했고, 누군가가 나를 도와 줄 수 있다면 정말 감사 할 것이다.
감사합니다.
편집! : 귄터의 대답에
솔루션 : 은 내가 HttpClient 구성 요소로 내 httpspinner-service 포장 대신 일반 HTTP 모듈의 그것을 사용. 여기 내 HttpClient 구성 요소입니다

import { Injectable } from '@angular/core'; 
import { Http, Headers } from '@angular/http'; 
import { SpinnerService} from './spinner-service'; 

@Injectable() 
export class HttpClient { 
    constructor(
     private http: Http, 
     public spinner: SpinnerService 
    ){ 

    } 

    createAuthorizationHeader(headers:Headers) { 
    headers.append('Authorization', 'Basic ' + btoa('username:password')); 
    } 

    get(url) { 
    this.spinner.start(); 
    let headers = new Headers(); 
    this.createAuthorizationHeader(headers); 
    return this.http.get(url, { headers: headers }).do(data=> {this.spinner.stop()}); 
    } 

    post(url, data) { 
    this.spinner.start(); 
    let headers = new Headers(); 
    this.createAuthorizationHeader(headers); 
    return this.http.post(url, data, { headers: headers }).do(data=> {this.spinner.stop()}); 
    } 
} 
+0

어쩌면 당신이 만드는 사용자 정의 서비스 :

//Imports import { Subscription } from 'rxjs/Subscription'; import { LoaderService } from './core/loader.service'; .. @Component({ selector: 'my-app', template: ' <div class="container-fluid content"> <router-outlet></router-outlet> </div> <spinner [visible]="displayLoader"></spinner> ' }) export class AppComponent implements OnInit, OnDestroy { displayLoader: boolean; loaderSubscription: Subscription; constructor(private loaderService: LoaderService) {} ngOnInit() { this.loaderSubscription = this.loaderService.loaderCounter.subscribe((counter: number) => { this.displayLoader = counter != 0; }); } ngOnDestroy() { this.loaderSubscription.unsubscribe(); } } 
  • 로더 서비스를 사용하여 각 요청. – Lekhnath

  • 답변

    6

    사이에 공유되는 서비스를 사용 Http (답가 이미 어떻게 자신의 클래스에 Http 포장에 대한)과 <spinner-component>. 는 참조 공유 서비스에서

    https://angular.io/docs/ts/latest/cookbook/component-communication.html 시작 (증가)의 카운터를 유지하고 완료/HTTP 요청을 실패 0에서 >0 또는 >0에서 0에 카운터 변경을 사용하거나 자체를 비활성화 할 때 <spinner-component> 때마다 통지 . 그냥 지금부터 여기 얻는 사람들을위한

    +0

    이것은 나에게 매우 유용한 답변이다. 고마워요! 최선을 다하고 Http를 래핑하면 문제가 해결되는지 아닌지 확인합니다. – ozata

    +0

    다시 고맙습니다! – ozata

    +0

    예제를 만들 수 있습니까? – gtzinos

    1

    ... 스피너는 HTTP 요청에 오류가 발생하는 경우에 멈추지 않을 것입니다이 솔루션을

    . 답변 귄터 Zöchbauer의에 대한

    ... 
    return this.http.post(url, data, { headers: headers }) 
        .do(data=> {this.spinner.stop()}, 
        err=> {this.spinner.stop()); 
    ... 
    
    3

    감사합니다, 내 필요에 따라 내장 예 : 다음 당신이 할 수 있도록 . 사용하기 쉽도록 HTTP 래퍼를 사용하지 않았지만이 예제는 카운터 제안에 따라 여러 서비스 호출과 함께 작동합니다. 희망이 누군가가 도움이 :)

    1. 로더 서비스를 만듭니다. 주요 구성 요소 파일에서

    2. (예 : AppComponent)는 변경에 가입하고에 반영 :

      import { Injectable } from '@angular/core'; 
      import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 
      
      @Injectable() 
      
      export class LoaderService { 
          public loaderCounter: BehaviorSubject<number> = new BehaviorSubject<number>(0); 
          displayLoader(value: boolean) { 
           let counter = value ? this.loaderCounter.value + 1 : this.loaderCounter.value - 1; 
           this.loaderCounter.next(counter); 
          } 
      } 
      
    3. 은 maain 모듈 파일 (AppModule 예)의 공급 업체에서 서비스를 포함 로더 (제 경우에는 별도의 구성 요소입니다).각도가 제공하는 HttpClass을 확장 HTTP 요청을 수행하고시 사용자 정의 서비스에`isBusy` 상태를 추적 할 수

      import { LoaderService } from './core/loader.service'; 
          .. 
          export class SampleComponent implements OnInit { 
           constructor(private _service: SomeService, private loader: LoaderService) { } 
      
          ngOnInit() { 
           this.loader.displayLoader(true); 
           this._service.getBalance().subscribe(
            response => ..do something.., 
            () => .. error.., 
            () => this.loader.displayLoader(false) 
           ); 
          } 
      } 
      
    +0

    매우 근사하지만 ... 아약스가 컴포넌트 내부에서 호출하는 이유는 무엇입니까? 나는 당신이 ajax 호출이 만들어진 다른 서비스의 내부에서 로더 서비스 메소드를 호출해야한다고 생각한다. – MadCatm2

    +0

    Angular 2에 대한 지식을 통해 서비스가 제공되며 구성 요소 레벨에서 가지고있는 값을 간단하게 호출하고 바인딩 할 수 있습니다. 구성 요소 내부의 모델/변수를 사용하여 응답을 바인드해야하므로 여러 서비스가 필요한 이유가 확실하지 않습니다. –