programing

Angular 8에서 서비스를 이용한 행동 주체 구현 방법

css3 2023. 6. 29. 20:17

Angular 8에서 서비스를 이용한 행동 주체 구현 방법

앵귤러는 처음이라 문제가 있어요.

저는 여러 형제 구성 요소로 앱을 만들고 있습니다.한 구성 요소의 값을 업데이트하면 다른 구성 요소가 업데이트되지 않습니다.저는 이 문제를 해결하기 위해 행동 주제를 사용해야 한다는 것을 알고 있습니다.하지만 서비스, 구성 요소 및 모든 템플릿을 사용하여 어떻게 구현할 수 있습니까?

여기 제 코드가 있습니다.

-----------------------------------------------------------------------------------------------------------

//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
        }
        })

    } 

}

-------------------------------------------------------------------------

//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();  
  }


}

간단한 방법을 보여드리겠습니다.

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

이제 응용프로그램의 아무 곳에서나 무언가를 업데이트할 때 변경사항을 다음과 같이 설정할 수 있습니다.ProfileService각 가입자가 변경사항을 수신합니다.에 가입하는 것을 추천합니다.ngOnInit.

ngOnInit() {
  this.profileService.getProfileObs().subscribe(profile => this.profile = profile);
}

메모리 누수를 방지하기 위해 관찰 가능한 항목의 구독을 취소하는 것을 잊지 마십시오!

그렇게 할 수 있는 방법은 여러 가지가 있습니다. --> 구독 사용 및 구독 취소ngOnDestroy()또는 다른 주제를 사용하여 다음과 같이 전달할 수 있습니다.

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

먼저 행동 주체 만들기

this._source = new BehaviourSubject<yourType>(initialValue);
this.source = this._source.asObservable();

BehaviorSubject를 "업데이트"하기 위한 함수 정의

updateSource(newValue) {
    this._source.next(newValue)
}

이제 구성 요소를 소스에 등록합니다.

this.service.source.subscribe();

Subject는 항상 초기 값을 필요로 하며 마지막 값을 내보냅니다.

DOCS: https://www.learnrxjs.io/subjects/behaviorsubject.html

httpRequest의 데이터를 공유하려면 shareReplay() 연산자를 대신 사용해야 합니다. 다른 구성 요소의 httpRequest에 가입하면 요청이 한 번 실행되고 데이터가 공유됩니다.

DOCS: https://www.learnrxjs.io/operators/multicasting/sharereplay.html

그렇게 하는 몇 가지 방법이 있습니다.그 중 하나가 여기에 설명되어 있습니다.

다음과 같이 서비스를 구축합니다.

// ReplaySubject is more flexible than BehaviorSubject, as it
// allows you to define how many past emissions should be available.
// But you can get an equivalent code with BehaviorSubject by
// coding like this:
// private _coachProfile$: BehaviorSubject<any | null> = 
//    new BehaviorSubject<any | null>(null);
private _coachProfile$: ReplaySubject<any> = new ReplaySubject<any>(1);

coachProfile(token :string)
{  
  return this.http.post<any>(this.apiURL+'/coach/profile_infos',{
    token: token,
  }).subscribe((profile) => this._coachProfile$.next(profile));        
}

subscribeToGetCoachProfile$()
{  
  return this._coachProfile$.asObservable();       
}

구성 요소의 경우:

ngOnInit() {
  this.coachService.subscribeToGetCoachProfile$()
    .subscribe((profile) => this.coachProfile = profile);
}

여러분이 생각할 수 있는 다른 접근법들이 있지만, 여러분이 질문에 붙여놓은 샘플 코드를 고려할 때 이것이 더 간단한 접근법이라고 생각합니다.

참고로 스택 오버플로에 대해 검색을 수행하면 여기에서 이 질문(또는 유사한 질문)이 여러 번 제기되었음을 알 수 있습니다.예를 들어, 이 다른 접근 방식의 경우: 공통 부품을 다시 계산하지 않고 여러 의 경우

동작 주체를 사용하여 문제를 해결하는 방법은 다음과 같습니다.

@Injectable()
export class CoachService {
  apiURL = environment.apiURL;

  constructor(private http: HttpClient) { }

  updateProfile(info, token, us_id): Observable<any> {
    return Observable.create((behaviorSubject: BehaviorSubject<any>) => {
      const requestData = {
        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
        }
      };
      const url = [this.apiURL, '/coach/update_profile'].join('');

      return this.http.post(url, requestData).subscribe(
        data => {
          behaviorSubject.next(data);
        },
        err => {
          behaviorSubject.error(err);
          if (err && err.status === 401) {
            // Do some err handling
          }
        }
      );
    });
  }

}

이제 데이터를 게시하고 행동 주체의 결과를 구독하려면 여기 있는 구성 요소의 에 다음과 같이 말합니다.

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

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

    },
      (err) => {
        // do some err handling
      });
} 

언급URL : https://stackoverflow.com/questions/57355066/how-to-implement-behavior-subject-using-service-in-angular-8