[英]Angular sharing data between two components
I am trying to share a value from one service to another componet but the value result is showing as undefined 我正在尝试将一项服务的价值共享给另一项服务,但价值结果显示为未定义
Injectable()
export class TestService {
url:string;
someExample(){
this.url="Hello";
}
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
constructor(private test: TestService,
) { }
doTest(){
console.log("CheckingValue"+ this.test.url)
}
}
How do I set url value so that I can receive on another component? 如何设置url值以便可以在其他组件上接收? I am new to angular I can see in console this.test.url values is showing as undefined 我是新手,可以在控制台中看到this.test.url值显示为未定义
you are calling a variable by just defining it so it's by default undefined
, so call a method which added a value to it. 您通过仅定义变量来调用变量,因此默认情况下为undefined
,因此请调用向其添加值的方法。
just add return
in your someExample() method 只需在您的someExample()方法中添加return
someExample() {
return this.url="Hello";
}
Example.component.ts Example.component.ts
doTest() {
console.log("CheckingValue"+ this.test.someExample())
}
Use Observable to subscribe for changes: 使用Observable订阅更改:
import { Observable, of } from 'rxjs';
Injectable()
export class TestService {
url:string;
someExample(): Observable<string>{
return of (this.url="Hello");
}
And get/ subscribe for it in the component: 并在组件中获取/订阅它:
this.testService.someExample().subscribe(result => {
console.log(result);
});
If the value changes in the service, you will get the updated value in the component. 如果服务中的值发生更改,您将在组件中获取更新的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.