【发布时间】:2019-03-16 21:10:40
【问题描述】:
我正在制作一个小应用程序,前面有 Angular7,背面有 Flask,我要做的是订阅服务,然后将返回的数据保存到我的主 AppComponent 内部的对象类型变量中,然后在我的所有其他组件中访问此变量。
API 服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
CheckApi(){
return this.http.get('http://localhost:5000/')
}
}
应用组件
import { Component, OnInit, Injectable } from '@angular/core';
import { ApiService } from './api.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Inbox App';
public text: object
constructor(private data: ApiService){}
ngOnInit(){
this.data.CheckApi().subscribe(data => {
this.text = data
console.log(this.text)
})
}
}
这是我试图从另一个组件中访问该对象的地方:
登录组件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
login.component.html
<section>
<legend class="text-center">{{ text }}</legend>
</section>
【问题讨论】:
-
@JasonWhite,感谢您的关注,但为什么
this.apiService.data;返回Observable对象而不是来自服务器的数据? -
我没有服务可以使用,你可以在CheckApi方法中放一个http调用并获取数据。我注释掉了 api 调用,以便有一个工作示例供您查看。
-
我用 api 调用更新了 stackblitz。未测试,因此您可能需要稍作修改。
-
我想我已经解决了,只需要先订阅它:)
标签: angular