【发布时间】:2021-05-03 13:05:17
【问题描述】:
我有一个简单的组件来测试字符串插值。在html中,
<p>{{value}}</p>
ts 文件:
export class HelloComponent implements OnInit {
value: any;
constructor(private service: ApiService) {
this.value = 'test';
}
ngOnInit() {
this.getValue();
}
getValue = (): void => {
this.value = this.service.getValue();
}
既然我已经注入了服务,那么让我们来看看吧。
@Injectable({
providedIn: 'root'
})
export class ApiService {
url: string;
value: any;
constructor(private http: HttpClient) {
this.url = 'http://localhost:8080/api/test';
}
getValue = () => {
this.http.get(this.url, {responseType: 'text'}).pipe(take(1)).subscribe(
data => {
this.value = data;
console.log(data); // 'Hello World' is printed out.
return data;
}
);
}
}
我的问题是我可以在控制台日志中看到正确的值。但我无法获得组件中的值。它是未定义的值,所以在屏幕上它什么都不是。
【问题讨论】:
标签: angular