2017-07-18 69 views
2
getPersonalMast(name:string){ 
     console.log("patient"); 
      this.masterDataService.getPersonalMast(this.staff).subscribe(console.log("Inside subscribe"), response => this.staffInfo = response); 
      return this.staffInfo; 
    } 

这是主服务称为角通话服务两次

getPersonalMast(personName: String): Observable<PersonalMastModel[]>{ 
console.log("patientInfo"); 
     let headers = new Headers();   
      if(personName!= undefined){ 
       headers.append(AppUtils.HEADER_AUTHENTICATION, localStorage.getItem(AppUtils.STORAGE_ACCOUNT_TOKEN)); 
       headers.append('Content-Type','application/json'); 
       headers.append('Access-Control-Allow-Origin', '*'); 
      return this.http.post(AppUtils.GET_PERSONAL_MASTER_URL ,{personName:personName},{headers:headers}) 

       .map(console.log("Inside map"),response => response.json().result) 
       .catch(this.handleError); 
      } 
    } 

有了这个服务,每次调用这个服务会导致多次击中的URL。

每个方法调用=多重服务调用。

为什么出现这种情况,我该如何解决这个问题?

调用服务代码:

<input ng2-auto-complete 
        [(ngModel)]="staff"     
        [source]="staffInfo" 
        placeholder="enter text" 
        [list-formatter]="listFormatter" 
        value-property-name="perscode" 
        display-property-name="personName" 
        (keypress)="getPersonalMast($event)" 
        > 
+1

您可以显示调用服务的代码? – DeborahK

+0

每次组件加载时服务调用的次数是2次,还是第一次调用服务时,第二次调用两次时,第三次调用三次时等,当您重新加载窗口或重新访问此组件时? –

+0

@DeborahK更新了问题 – user630209

回答

1

通常这种行为是订阅的可观,而不是当你破坏了组件退订的结果,因此预订仍然存在,当再次部件载荷,可观察的响应多倍到组件的请求。这些订阅积累。

为了防止这种情况,并防止内存泄漏,当你摧毁的每个组件,你应该退订观测。

这些进口添加到您的组件

import 'rxjs/add/operator/takeUntil'; 
import { Subject } from 'rxjs/Subject'; 

在你的类添加这个 - 我通常做这种构造之上。

private ngUnsubscribe: Subject<any> = new Subject<any>() 

添加ngOnDestroy功能

ngOnDestroy() { 
    this.ngUnsubscribe.next(); 
    this.ngUnsubscribe.complete(); 
    } 

然后你.subscribe

.takeUntil(this.ngUnsubscribe) 

所以你的情况,它看起来像在此之前立即添加此。

getPersonalMast(姓名:字符串){ console.log(“this.staff”+ JSON.stringify(this.staff));

this.masterDataService.getPersonalMast(this.staff) 
     .takeUntil(this.ngUnsubscribe) 
     .subscribe(response => this.staffInfo = response); 
     return this.staffInfo; 
} 

所以会发生什么是订阅将保持活动状态,直到从组件导航离开,此时ngOnDestroy其从可观察退订干净火灾。

编辑:根据您的HTML

的夹杂物。如果你在你的模板中的错误,例如未关闭标签:

<div><div>而不是<div></div>

或者,如果默认类型(提交),你可能会看到此行为按钮提交您的形式离开了。

<button type="button" (click)="submitForm()"> 

相反的:

<button (click)="submitForm()"> or <button type="submit" (click)="submitForm()"> 
+0

实现所有你提到的,仍然调用两次。 – user630209

+0

在if(personName!= undefined){...}块中的服务中放置一个console.log语句,如“设置标题”,然后查看哪些标题消息和this.staff消息出现在控制台上。 –

+0

我有一个主服务,它调用Web服务。另一种方法是从组件调用它,我称之为主服务。由于我给出的名字都相同,所以可能会感到困惑。因此,我在这里提到了我已经添加到组件的内容。我需要在Master中添加这个吗? – user630209