问题描述: 在Angular中,需要将字符串返回给组件,但是数据没有返回。
解决方法:
例如,在组件的HTML模板中:
{{ myString }}
在组件的typescript文件中:
myString: string = "Hello, Angular!";
例如,在组件的HTML模板中:
在组件的typescript文件中:
myString: string = "Hello, Angular!";
例如,创建一个名为"StringService"的服务:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StringService {
getString(): string {
return "Hello, Angular!";
}
constructor() { }
}
然后,在组件的typescript文件中注入该服务,并调用其方法获取字符串数据:
import { Component, OnInit } from '@angular/core';
import { StringService } from 'your-service-path';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
myString: string;
constructor(private stringService: StringService) { }
ngOnInit() {
this.myString = this.stringService.getString();
}
}
在组件的HTML模板中,使用数据绑定将获取到的字符串显示在页面上:
{{ myString }}
以上是三种常见的解决方法,根据具体的需求和场景选择合适的方法即可。