Angular привязка не обновляется при получении данных от сервиса - PullRequest
0 голосов
/ 24 февраля 2020

В моем приложении Angular я использую сервис, который получает данные из моего API, защищенного с помощью OAuth2. Я использую MSAL для Angular для аутентификации пользователя.

Когда данные возвращаются службой в первый раз после получения токена доступа, привязка не обновляется в шаблоне компонента. Это происходит только после входа в приложение. Если я перефразирую sh страницу, переплет работает.

MyComponent код:

@Component({
    selector: 'app-mycomponent',
    template: '<span *ngIf="currentUser">{{currentUser.DisplayName}}</span>'
})
export class MyComponent implements OnInit {
    public currentUser: User;

    constructor(private dataService: MyDataService) { }

    ngOnInit() {  
        this.dataService.getUser().subscribe((response: User) => {
            this.currentUser = response;  // this.curentUser is not updated in the template
            console.log(this.currentUser); // (1)
        }, (error) => { 
            console.error(error);
        }, () => {
            console.log(this); // (2)
        });
    }
}

MyComponent помещается в AppComponent:

@Component({
    selector: 'app-root',
    template: '<app-mycomponent *ngIf="isAuthenticated"></app-mycomponent>
               <router-outlet></router-outlet>'
})
export class AppComponent implements OnInit, OnDestroy {
    public isAuthenticated: boolean;
    private msalSub: Subscription;

    constructor(
       private broadcastService: BroadcastService, 
        private authService: MsalService) { }

    ngOnInit() {
        if (this.authService.getUser()) {
            this.isAuthenticated = true;
        }

        this.msalSub = this.broadcastService.subscribe("msal:loginFailure", (payload) => {
            console.log("Login failure in AppComponent. " + JSON.stringify(payload));
            this.authService.loginRedirect();
        });

        this.msalSub = this.broadcastService.subscribe("msal:loginSuccess", (payload) => {
            console.log("Login success in AppComponent. " + JSON.stringify(payload));
        });
    }

    ngOnDestroy() {
        this.broadcastService.getMSALSubject().next(1);
        if (this.msalSub) {
            this.msalSub.unsubscribe();
        }
    }
}

User класс:

export class User {
    Id: number;
    Guid: string;
    DisplayName: string;
}

MyDataService:

@Injectable({
    providedIn: 'root'
})
export class MyDataService {
    private currentUser: User;

    constructor(private authService: MsalService, private http: HttpClient) { }

    public getUser(): Observable<User> {
        if (this.currentUser === undefined) {
            return this.httpGetRequest("https://localhost:1234/me/")
                .map((response: User) => {
                    this.currentUser = response;
                    return response;
                });
        } else {
            return Observable.of(this.currentUser);
        }
    }

    private httpGetRequest(url: string): Observable<object> {
        console.warn("GET: " + url);
        return this.http.get(url)
            .map(response => {
                console.log(response);
                return response;
            })
            .catch(response => (Observable.throw(response)))
    }
}

Журнал консоли (1) показывает данные пользователя, полученные от службы, и последний журнал (2) показывает, что компонент имеет свойство currentUser с правильными данными, но значение не обновляется в шаблоне.

(1) вывод журнала:

{Id: 1, Guid: "18740e56-1165-4e7c-ae27-1b4e2442cd43", DisplayName: "Test User"}

Я просмотрел несколько других вопросы, связанные с проблемами связывания, но я не нашел никакого решения.

...