【问题标题】:Wait angular response to load before using it in multiple components在多个组件中使用之前等待加载的角度响应
【发布时间】:2019-03-07 14:17:22
【问题描述】:

我有一个从我的服务器加载数据的服务,我想在这个服务中得到一个响应,该响应将被多个组件访问。问题是,我必须等待 http 响应到达。我知道我可以订阅 Observable,但是如果我在我拥有的所有组件中订阅它,它将在每个组件中加载它。 我希望能够等到它加载到任何组件中。

这是我的服务:

KalidataService

export class KalidataService {
  public response: any = null;

  constructor(private http: Http) {
    this.getResponse();
  }

  getResponse() {
    const url = 'http://url.com';

    const params = new URLSearchParams();

    params.append('login', 'login');

    params.append('senha', 'pass');

    this.http.post(url, params).subscribe(
      response => this.response = response.json(),
      error => console.log('ERROR')
    );

  }
}

这是我的组件之一:

export class DiarioComponent implements OnInit {
  nome_usario: string;
  materias: Materia[];


  constructor(private kalidataService: KalidataService) {
  }

  log() {
    console.log(this.kalidataService.response);
  }

  ngOnInit() {
  }

}

例如:我在一个按钮中有登录功能,当我在加载页面后立即单击时,如果我单击它会在一段时间后记录“空”记录响应。

【问题讨论】:

  • 在路由中使用解析器??
  • 看看BehaviorSubjects,这是一种让组件相互通信的好方法。或者在路由中使用解析器,或者如果您在身份验证时遇到问题,只需使用 Guard

标签: angular angular6


【解决方案1】:

您可以使用 Subject/BehaviorSubject() 实现此目的。

KalidataService

private subjectData = new Subject<any>();
public subjectData$ = this.subjectData.asObservable();

getResponse() {
    const url = 'http://url.com';

    const params = new URLSearchParams();

    params.append('login', 'login');

    params.append('senha', 'pass');

    this.http.post(url, params).subscribe(
      response => {
        this.response = response.json();
        this.subjectData.next(this.response);
      },
      error => console.log('ERROR')
    );

  }

日记组件

ngOninit(){
   this.kalidataService.subjectData$.subscribe((response)=>{
       console.log(response);
   });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多