如何在 Angular 8 中使用服务实现行为主体

kkD*_*D97 19 httpclient typescript behaviorsubject angular angular8

我是 Angular 的新手,但遇到了问题。

我正在创建一个包含多个兄弟组件的应用程序。当我更新一个组件中的值时,其他组件不会更新。我知道要解决这个问题,我应该使用行为主题。但是我如何用我的服务、组件和所有模板来实现它?

这是我的代码 -

---------------我的服务-------------------------- ——

//import


@Injectable() 
export class CoachService {

    apiURL = environment.apiURL;

    constructor(private http: HttpClient ) { }

    coachProfile(token :string)
    {  
    return this.http.post<any>(this.apiURL+'/coach/profile_infos',{
      token: token
      })        
    }

    updateProfile(info: any, token: string, us_id: string) {
      return this.http.post<any[]>(this.apiURL + '/coach/update_profile', {
        token: token,
        us_id: us_id,
        us_lang: info.us_lang,
        us_firstname: info.us_firstname,
        us_lastname: info.us_lastname,
        us_sex: info.us_sex,
        us_birthdate: info.us_birthdate,
        us_national_number : info.us_national_number,
        us_email: info.us_email,
        us_gsm: info.us_gsm,        
        online_profile: info.online_profile,          
        us_address: info.us_address,
        us_zip: info.us_zip,
        us_city: info.us_city,
        country:{
          id: info.country.id
        }
        })

    } 

}
Run Code Online (Sandbox Code Playgroud)

----------一个组件.ts -----------

//import
//component decorator

export class CoordonneesComponent implements OnInit, OnDestroy {

private coachProfile;
  token: string = localStorage.getItem('token');
  us_id : string;
  us_lang: string; 
  infos_profile: any;
  online: any;


  constructor(private translate: TranslateService,private coachService: CoachService, private router: Router) { }

  ngOnInit() {

    this.coachProfile=this.coachService.coachProfile(this.token)
      .subscribe((data) => {
        this.infos_profile = data.results;
        this.online = this.infos_profile.online_profile;
        this.translate.use(this.infos_profile.us_lang)
        this.infos_profile.lang= this.infos_profile.us_lang;

      });

   .....
  }


updateCoordonees() {
  this.coachService.updateProfile(this.infos_profile, this.token, this.us_id)
    .subscribe((data: any) => {

      if(data.success && data.msg!=null)
      { 
  // do something
      }
      else
      {
       // do something
      }

    },
      (err) => {
        // do something
      });

}  



  ngOnDestroy() {
    this.countrieList.unsubscribe();
    this.coachProfile.unsubscribe();  
  }


}

Run Code Online (Sandbox Code Playgroud)

sag*_*gat 30

我将向您展示一个简单的方法:

@Injectable() 
export class ProfileService {

    private profileObs$: BehaviorSubject<Profile> = new BehaviorSubject(null);

    getProfileObs(): Observable<Profile> {
        return this.profileObs$.asObservable();
    }

    setProfileObs(profile: Profile) {
        this.profileObs$.next(profile);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当您在应用程序中的任何位置更新某些内容时,您可以通过ProfileService每个订阅者接收更改来设置该更改。我建议你订阅ngOnInit

ngOnInit() {
  this.profileService.getProfileObs().subscribe(profile => this.profile = profile);
}
Run Code Online (Sandbox Code Playgroud)

永远不要忘记取消订阅 observable 以防止内存泄漏!

有很多方法可以做到这一点 --> 使用订阅并取消订阅ngOnDestroy()或使用另一个主题并将其交付给 takeUntil,如下所示:

unsubscribe$: Subject<boolean> = new Subject();

...

ngOnInit() {    
  this.profileService.getProfileObs()
                     .pipe(takeUntil(this.unsubscribe$))
                     .subscribe(profile => this.profile = profile);
}

ngOnDestroy() {
  this.unsubscribe$.next(true);
  this.unsubscribe$.complete();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

首先创建一个BehaviourSubject

this._source = new BehaviourSubject<yourType>(initialValue);
this.source = this._source.asObservable();
Run Code Online (Sandbox Code Playgroud)

定义一个函数来“更新”BehaviourSubject

updateSource(newValue) {
    this._source.next(newValue)
}
Run Code Online (Sandbox Code Playgroud)

现在在您的组件中订阅源

this.service.source.subscribe();
Run Code Online (Sandbox Code Playgroud)

请注意,behaviorSubject 始终需要一个初始值并发出最后一个值

文档: https: //www.learnrxjs.io/subjects/behaviorsubject.html

如果您想共享来自 httpRequest 的数据,您应该使用 shareReplay() 运算符,您可以从不同的组件订阅 httpRequest,并且将发出一次请求并共享数据

文档: https: //www.learnrxjs.io/operators/multicasting/sharereplay.html