component1. html
<p>comp1 works!</p>
<div>
<input type="text" #uname>
<button (click)="updateUserName(uname)">submit</button>
<h1>{{name}}</h1>
</div>
component1.component.ts
import { Component, OnInit } from "@angular/core";
import { DataService } from "../app.service/data.service";
@Component({
selector: "app-comp1",
templateUrl: "./comp1.component.html",
styleUrls: ["./comp1.component.css"]
})
export class Comp1Component {
name: any;
constructor(private _service: DataService) {
this._service.userName.subscribe(uname => {
this.name = uname;
});
}
updateUserName(uname) {
this.name = uname.value;
this._service.userName.next(uname.value);
}
}
приложение .service
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
@Injectable({
providedIn: "root"
})
export class DataService {
userName: any;
constructor() {
userName: new Subject<any>();
}
}
comp2. html
<p>comp2 works!</p>
<h2>{{name}}</h2>
comp2.component.ts
import { Component, OnInit } from "@angular/core";
import { DataService } from "../app.service/data.service";
@Component({
selector: "app-comp2",
templateUrl: "./comp2.component.html",
styleUrls: ["./comp2.component.css"]
})
export class Comp2Component implements OnInit {
name: string;
constructor(private _service: DataService) {
this._service.userName.subscribe(arg => (this.name = arg));
}
ngOnInit() {}
}
Я столкнулся с проблемой браузера
main.ts:12 TypeError: Cannot read property 'subscribe' of undefined
at new Comp1Component (comp1.component.ts:13)
at createClass (core.js:31987)
at createDirectiveInstance (core.js:31807)
at createViewNodes (core.js:44210)
at callViewAction (core.js:44660)
at execComponentViewsAction (core.js:44565)
at createViewNodes (core.js:44239)
at createRootView (core.js:44082)
at callWithDebugContext (core.js:45632)
at Object.debugCreateRootView [as createRootView] (core.js:44848)
- Я создал службу и определил свойство userName
- из comp1, обновив userName
- поэтому можно увидеть результат в comp2 по подписке
- в comp1.component.ts Я использую имя свойства для обновления userName