在Angular中为单个组件调用多个服务

时间:2017-10-05 16:22:36

标签: angular

enter image description here

我以角度调用了单个服务但从未调用过多个服务。 在我附加的图像中,要求是将客户端和组值添加到名为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');
          } 

   }

}

有人可以告诉我应该考虑的方法吗?

3 个答案:

答案 0 :(得分:5)

您可以通过多种方式执行此操作。您可以使用 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;               
 });

答案 1 :(得分: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
});

最后,如果你想一个接一个地运行但在最终订阅中需要两个结果,那么你可以使用上述的组合:

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

有关详细信息,请参阅:combineLatestconcatMap

答案 2 :(得分:0)

真正的问题是为什么在不同的终端? 如果其中一个失败,或者最后一个失败? 你如何回滚上一个交易?

将此操作视为原子操作。将所有数据发布到服务器,让服务器将其拆分为表或需要完成的任何操作。