Не удается прочитать свойство «подписаться» на неопределенное в браузере - PullRequest
1 голос
/ 27 марта 2020

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)
  1. Я создал службу и определил свойство userName
  2. из comp1, обновив userName
  3. поэтому можно увидеть результат в comp2 по подписке
  4. в comp1.component.ts Я использую имя свойства для обновления userName

1 Ответ

0 голосов
/ 27 марта 2020

Из того, что я вижу в вашем коде в вашем сервисе, у вас есть эта строка в конструкторе:

userName: new Subject<any>();

Мне интересно, почему машинопись не жалуется на это. Там у вас должно быть задание:

this.userName = new Subject<any>();

или вы можете сделать это так:

 export class DataService {
     private userName = new Subject<any>();
     public userName$ = this.username.asObservable();

    // you should move your update method in the service
     updateUserName(uname) {
        this.userName.next(uname.value);
      }
   }

и в вашем компоненте:

// use life cycle hooks instead of the constructor for this kind of operations
ngOnInit() {
  this._service.userName$.subscribe(arg => (this.name = arg));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...