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

在Angular中为单个组件调用多个服务,angular,Angular,我在angular中调用了单个服务,但从未调用过多个服务。 在我所附的图像中,要求将客户机和组值添加到名为clientGroup Xref的表中。此外,客户机、Clientrole和ClientKey也位于不同的表中(ClientService将执行此操作)。我想知道如何在单击“创建”按钮时同时调用clientservice和clientgroup外部参照服务 This is the code I tried so far import { Router } from '@angular/ro

我在angular中调用了单个服务,但从未调用过多个服务。 在我所附的图像中,要求将客户机和组值添加到名为clientGroup Xref的表中。此外,客户机、Clientrole和ClientKey也位于不同的表中(ClientService将执行此操作)。我想知道如何在单击“创建”按钮时同时调用clientservice和clientgroup外部参照服务

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');
          } 

   }

}
这是我到目前为止尝试的代码
从'@angular/Router'导入{Router};
从“/auth.service”导入{AuthService};
从“/pes_auth.service”导入{PESAuthService};
从“@angular/core”导入{Component,OnInit,Injectable};
从'@angular/Http'导入{Http,Request,RequestMethod,RequestOptions,Headers,Response};
从“rxjs/Observable”导入{Observable};
从“/../../shared/models/Client”导入{Client};
@可注射()
导出类ClientService实现OnInit{
私有appContent='application/json';
专用路由器:路由器;
专用baseUrlhttp://localhost:5050/api/v1/';
//构造函数初始化authService以对用户进行身份验证,http发送CRUD请求,路由器为资源
构造函数(私有authService:authService,私有http:http,私有路由器:路由器,私有pesauthservice:pesauthservice){
}
恩戈尼尼特(){
}
//要创建用户客户端,必须传递Key、Firstname和lastName
//创建日期:日期
create(client:string,clientkey:string,clientrole:string):可观察{
//在发送Http请求之前调用createAuthenticatedRequest
让request=this.createAuthenticatedRequest(JSON.stringify({client:client,clientkey:clientkey,clientrole:clientrole}),RequestMethod.Post);
返回这个.http.request(request.map)(r=>{
r、 嗯,;
}).catch((错误:任意)=>{
返回可观察抛出(错误);
});
}
更新(id:number,client:string,clientKey:string,clientRole:string,created:Date):可观察{
let request=this.createAuthenticatedRequest(JSON.stringify(
{id:id,client:client,clientKey:clientKey,clientRole:clientRole,created:created}),RequestMethod.Put,id.toString();
返回这个.http.request(request.map)(r=>{
r、 json;
控制台日志(r);
}).catch((错误:任意)=>{
console.log(错误);
返回可观察抛出(错误);
});
}
删除(客户端:字符串,客户端键:字符串,客户端角色:字符串,创建日期):可观察{
让request=this.createAuthenticatedRequest(JSON.stringify({client:client,clientkey:clientkey,clientrole:clientrole,created:created}),RequestMethod.Delete);
返回这个.http.request(request.map)(r=>{
r、 嗯,;
}).catch((错误:任意)=>{
返回可观察抛出(错误);
});
}
//Read方法接受一个可选的输入id,如果id没有传递给Read,它将获得整个列表,否则它将获得具有指定id的记录
读取(id?:编号):可观察{
id=(id==未定义)?0:id;
如果(id>0)
//从集合中获取单个资源
var request=this.createAuthenticatedRequest(null,RequestMethod.Get,id.toString());
其他的
//获取整个集合
request=this.createAuthenticatedRequest(null,RequestMethod.Get,id.toString());
返回这个.http.request(request.map)(r=>{
console.log(r.text());
返回JSON.parse(“[”+r.text()+“])[0];
}).catch((错误:任意)=>{
返回可观察抛出(错误);
});
}
//此方法接受attribtes客户机、key、firstname和lastName的json以及请求方法(Post/Get/Put/delete)和
//可选参数id,此方法的返回类型为Request
createAuthenticatedRequest(json:string,reqMethod:RequestMethod,optionalparam?:string):请求{
//检查用户是否已通过身份验证,身份验证服务方法为isAuthenticated
if(this.authService.isAuthenticated()){
if(this.peAuthService.ispeAuthenticated())
{
console.log('authenticated');
//创建一个请求对象,其方法、url和主体由客户机、键、firstname和lastName以及可选参数id组成
optionalparam=(optionalparam==未定义的| | optionalparam=='0')?“”:optionalparam;
const请求=新请求({
方法:reqMethod,
url:this.baseUrl+'clients/'+optionalparam+“”,
正文:json
});
//添加请求头授权以指定请求具有经过身份验证的令牌
append('Authorization'、'Bearer'+this.pesauthservice.getToken());
request.headers.append('Content-Type',this.appContent);
request.headers.append('Accept',this.appContent);
返回请求;
}  
否则{
console.log('notauthenticated');
这是._router.navigateByUrl('/login');
} 
}    
否则{
console.log('notauthenticated');
这是._router.navigateByUrl('/login');
} 
}
}

有人能告诉我我应该考虑的方法吗? 有很多方法可以做到这一点。你可以使用

对象。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;               
 });

真正的问题是,为什么要在不同的端点上执行此操作? 如果其中一个失败,或者准确地说,最后一个失败? 如何回滚上一个事务

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

如果要运行
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
    });
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.
});