有角度地在两个组件之间共享数据

时间:2019-05-07 12:07:28

标签: angular angular-components

我正在尝试将一项服务的价值共享给另一项服务,但价值结果显示为未定义

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)
  }
}

如何设置url值以便可以在其他组件上接收?我是新手 我可以在控制台中看到this.test.url值显示为未定义

2 个答案:

答案 0 :(得分:0)

您只是通过定义变量来调用变量,因此默认情况下为 undefined ,因此请调用为变量添加值的方法。

只需在您的 someExample()方法中添加 return

someExample() {
   return  this.url="Hello";
}
  

Example.component.ts

doTest() {    
  console.log("CheckingValue"+ this.test.someExample())
}

答案 1 :(得分:0)

使用Observable订阅更改:

import { Observable, of } from 'rxjs';

Injectable()
export class TestService {
 url:string;

someExample(): Observable<string>{
 return of (this.url="Hello");
}

并在组件中获取/订阅它:

this.testService.someExample().subscribe(result => {
 console.log(result);
});

如果服务中的值发生更改,您将在组件中获取更新的值。

相关问题