2017-10-05 26 views
2

enter image description here爲Angular中的單個組件調用多個服務

我已經調用了單個服務,但從未調用過多個服務。 在我附加的圖像中,要求是將客戶端和組值添加到名爲clientGroup Xref的表中。另外客戶端,Clientrole,ClientKey在不同的表中(ClientService會這樣做)。我想知道如何在創建按鈕單擊時同時調用clientservice和clientgroup Xref服務。

This is the code I tried so far 
import { Router } from '@angular/router'; 
import { AuthService } from './auth.service'; 
import {PESAuthService} from './pes_auth.service'; 
import { Component, OnInit, Injectable } from '@angular/core'; 
import { Http, Request, RequestMethod, RequestOptions, Headers, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import {Client} from './../../shared/models/Client'; 

@Injectable() 
export class ClientService implements OnInit { 
    private appContent = 'application/json'; 
    private _router: Router; 
    private baseUrl = 'http://localhost:5050/api/v1/'; 

    //Constructor to initialize authService to authenticate user, http to send the CRUD request and Router for the resource 
    constructor(private authService: AuthService, private http: Http,private router: Router,private pesauthservice: PESAuthService) { 
    } 
    ngOnInit() { 
    } 

    //For creating a user Client,Key,Firstname and lastName has to be passed 
// created: Date 
    create(client: string, clientkey: string, clientrole: string) :Observable<boolean> { 
     //createAuthenticatedRequest is called before sending the Http request 
     let request = this.createAuthenticatedRequest(JSON.stringify({client: client, clientkey: clientkey, clientrole: clientrole}),RequestMethod.Post); 

     return this.http.request(request).map(r=>{ 

      r.ok; 
     }).catch((error: any) =>{ 
     return Observable.throw(error); 
     }); 

    } 
    update(id: number,client: string, clientKey: string, clientRole: string, created: Date) :Observable<any> { 

     let request = this.createAuthenticatedRequest(JSON.stringify(
      {id:id,client: client, clientKey: clientKey, clientRole: clientRole, created: created}),RequestMethod.Put,id.toString()); 
     return this.http.request(request).map(r=>{ 
      r.json; 
      console.log(r); 
     }).catch((error: any) =>{ 
      console.log(error); 
     return Observable.throw(error); 
     }); 

    } 
    delete(client: string, clientkey: string, clientrole: string, created: Date):Observable<boolean> { 

    let request = this.createAuthenticatedRequest(JSON.stringify({client: client, clientkey: clientkey, clientrole: clientrole, created: created}),RequestMethod.Delete); 
     return this.http.request(request).map(r=>{ 
      r.ok; 
     }).catch((error: any) =>{ 
     return Observable.throw(error); 
     }); 

    } 

    //Read method takes an optional input id, If id is not passed to read it will get the entire list , else it will get the record with specified id 
    read(id?: Number):Observable<any> { 

     id = (id == undefined) ? 0 : id ; 

     if (id >0) 
      // Get single resouce from Collection 
      var request = this.createAuthenticatedRequest(null,RequestMethod.Get, id.toString()); 
     else 
      // Get the entire collection 
      request = this.createAuthenticatedRequest(null,RequestMethod.Get, id.toString()); 

     return this.http.request(request).map(r=>{ 
      console.log(r.text()); 
      return JSON.parse("[" + r.text() + "]")[0]; 
     }).catch((error: any) =>{ 
     return Observable.throw(error); 
     }); 
    } 



    //This method accepts json of the attribtes client,key,firstname and lastName and request method(Post/Get/Put/delete) and 
    //an optional parameter id , This method's return type is Request 
    createAuthenticatedRequest(json : string, reqMethod: RequestMethod, optionalparam?: string) : Request{ 
     //checks if the user is authenticated user with authentication service method isAuthenticated 
     if (this.authService.isAuthenticated()) { 

      if(this.pesauthservice.isPESAuthenticated()) 
      { 

      console.log('authenticated'); 
      //creating a request object with method,url and body consisting of client,key,firstname and lastName and optional parameter id 
      optionalparam =(optionalparam==undefined || optionalparam =='0') ? "" : optionalparam; 
      const request = new Request({ 
       method: reqMethod, 
       url: this.baseUrl + 'clients/' + optionalparam +"", 
       body: json 
       }); 
       //request header Authorization is added to specify that the request has an authenticated token 
      request.headers.append('Authorization', 'Bearer ' + this.pesauthservice.getToken()); 
      request.headers.append('Content-Type', this.appContent); 
      request.headers.append('Accept', this.appContent); 
      return request; 
      } 
      else { 
      console.log('notauthenticated'); 
      this._router.navigateByUrl('/login'); 
      } 
     }  

     else { 
      console.log('notauthenticated'); 
      this._router.navigateByUrl('/login'); 
      } 

    } 

} 

有人可以告訴我我應該考慮的方法。

+0

使用[Observables](https://rahulrsingh09.github.io/AngularConcepts/ngrx/rxjs)檢查此鏈接將對您有所幫助。 –

回答

4

有很多方法可以做this.You可以使用Observable.forkjoinObservable.merge

Object.forkJoin將等到所有的請求都完成了,然後就可以構建這個結果的單一列表;

舉例forkjoin

const allrequests = Observable.forkJoin(
    this.http.get('https://testdb1.com/.json').map((res: Response) => res.json()), 
    this.http.get('https://testdb2.com/.json').map((res: Response) => res.json()) 
) 
allrequests.subscribe(latestResults => { 
      const [ data_changes , data_all ] = latestResults;    
}); 
+0

嗨Sajeetharan請你分享一些例子。 –

+0

https://stackoverflow.com/questions/43166214/merging-http-observables-using-forkjoin – Sajeetharan

+0

你能告訴我在同一個組件中有多不同的字段(在圖像中,我使用Client共享Client,ClientKey,ClientRole到一個表服務和客戶端和組到其他服務ClientGroupXref服務)被傳遞到其他領域,我仍然不明白從stackoverflow鏈接,它是我得到的時候,我谷歌相同的鏈接。 –

0

真正的問題是爲什麼做它在不同的端點? 如果其中一個會失敗,或者最後一個是精確的? 你如何回滾以前的交易?

將此操作視爲原子操作。將所有數據發佈到服務器,讓服務器將其分爲表或任何需要完成的工作。

2

如果要同時運行2個請求並獲得綜合作用的結果,當兩個完整的,你可以使用combineLatest像這樣:

const updateClient$ = this.clientService.update(...); 
const updateGroup$ = this.clientXrefGroupService.update(...); 
Observable.combineLatest(updateClient$,updateGroup$) 
    .subscribe(combinedResult => { 
     // Here combinedResult is an array. 
     // Index 0 contains response from updateClient$ request 
     // Index 1 contains response from updateGroup$ request 
    }); 

如果你想運行請求一前一後(爲例如,如果你想使用的結果第一次調用,以便使第二),可以使用concatMap

updateClient$.concatMap(resultOfUpdateClient => { 
    return updateGroup$; 
}).subscribe(resultOfUpdateGroup => { 
    // Do your stuff here 
}); 

最後,如果你想運行一個接一個,但需要在最後認購兩個結果那麼你可以使用組合上述的N:

updateClient$.concatMap(resultOfUpdateClient => { 
    return Observable.combineLatest(updateGroup$, Observable.of(resultOfUpdateClient)); 
}).subscribe(combined => { 
    // Here combined is an array containing the result of both calls. 
}); 

更多信息參見:combineLatestconcatMap

相關問題