手动刷新页面时,Observable不保存数据

问题描述 投票:1回答:1

我在我的服务构造函数中有这个代码:

this.getUser().subscribe( data => this.user = data.text(), error => console.log(error) );

当我的应用程序使用路由器链接(从菜单)导航时,此代码可以正常工作,但是当手动刷新页面时... data.text()包括登录用户(如果我将其打印到控制台,我可以看到它)但是这样.user变量没有保存它,它仍然是“未定义”!

到目前为止,我尝试使用setTimeout或BehaviorSubject,但没有运气:

private _subject = new BehaviorSubject<any>([]);
subject$ = this._subject.asObservable();
this.getUser().subscribe( data => 
        //setTimeout(() => { this.user = data.text() }, 1000),
          this.user = this._subject.next(data),
                error => console.log(error) );

Update:

app.component.ts

import { Component, ViewEncapsulation, Output, EventEmitter } from '@angular/core';
import { ResourcesService } from './services/resources.service';
import { PrivilegeService } from './services/privilege.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
user: string;
constructor(
        private resourcesService: ResourcesService,
        private privilegeService: PrivilegeService
        ) { 

    if (Config.PROD_MODE)
        resourcesService.getUser().subscribe( data => {
            this.user = data.text(); 
            resourcesService.user = data.text();
        }, error => {console.log(error);

resource.service.ts:

  constructor(public http: Http){ 
  this.headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
  this.options = new RequestOptions({ headers: this.headers});}


/**
 * Get current user
 */
getUser(){
    let url = this.url + "user";  

    return this.http.get(url)
        //.catch( (error: any) => { console.log(error); return Observable.empty<Response>();} );
        .catch( (error: any) => Observable.throw(error || 'Server Error - could not get user') );
}

privilege.service.ts:

@Injectable()
export class PrivilegeService extends ResourcesService {
constructor(public http: Http){ 

  super(http);

  this.user = '';

资源list.component:

public constructor(private resourcesService: ResourcesService,
                    private privilegeService: PrivilegeService, 
                    private router: Router, private route: ActivatedRoute) {

    if (Utils.isEmpty(this.resourcesService.user)){
        this.resourcesService.getUser().subscribe( data => {
            this.resourcesService.user = data.text();
            this.callGetResources();
        }, error => console.log(error) );
    }
}

我试着在可观察块中调用get资源调用,现在我得到了:

ERROR错误:InvalidPipeArgument:''对于管道'AsyncPipe'在invalidPipeArgument错误(common.es5.js:2610)处AsyncPipe.webpackJsonp ... / .. / .. / common/@angular/common.es5.js.AsyncPipe。 _selectStrategy(common.es5.js:2755)

我意识到在设置resources.service的用户变量之前执行了对getResources()的调用:

  1. 在app.component中,执行了对getUser()的调用,但数据仍未准备就绪。在调试时,我可以看到如下数据:

消息:“意外的输入结束”堆栈:“SyntaxError:新的AppComponent(http://localhost:8080/DataFabResourceManager/dist/main.bundle.js:247:9)上的输入意外结束”↵

  1. 然后调用getResources()从资源列表页面(我刷新时站起来)。但此时用户仍未定义
  2. 回到app.component,现在数据准备就绪,资源服务的用户变量是坐的(但为时已晚):

200 statusText:“OK”输入:2 url:“http://localhost:8080/DataFabResourceManager/management/user”_body:“regressiontester_db”proto

angular observable
1个回答
0
投票

尝试做以下事项:

在你的服务创建函数,它将返回observable:

getUser() {
    return http.get('here your rest api link to back-end');
}

然后从组件中调用该方法,例如从ngOnInit()方法调用。 (您可以从angular.io获得官方指南):

ngOnInit() {
    this.service.getUser().subscribe('here your subscribe logic'); 
}

还为您的服务提供HttpClient作为构造函数参数。然后通过构造函数将您的服务提供给组件。

有用的网址:

https://angular.io/guide/dependency-injection

https://angular.io/guide/dependency-injection-pattern

http:https://angular.io/api/common/http/HttpClient

© www.soinside.com 2019 - 2024. All rights reserved.