Как я могу отправить объект на не связанный компонент через сервис в Angular 6? - PullRequest
2 голосов
/ 14 марта 2019

Итак, я новичок в Angular и пытаюсь отправить объект из component1 в component2 с помощью службы.Когда я записываю результат в консоль в component2, он не дает мне обновленное значение объекта, и это, вероятно, потому, что служба повторно инициализируется во втором компоненте.Можете ли вы помочь в этом вопросе?

Это мой код

 @Injectable({
  providedIn: 'root'
})
export class CodeServiceService {
  codeInfo:Code={
    name:"",
    text:"",
    type:0
  };
  getCode(){
    console.log(this.codeInfo);
    return this.codeInfo;
  }
  setCode(result:Code){
    this.codeInfo=result;
  }
}

Компонент1

@Component({
  selector: 'app-newscan',
  templateUrl: './newscan.component.html',
  styleUrls: ['./newscan.component.css'],
  providers:[CodeServiceService]
})
export class NewscanComponent implements OnInit {
scannedCode:Code={
    name:"name",
    text:"text",
    type:1
  };

  constructor(private service:CodeServiceService){}
saveInfo(){
    this.service.setCode(this.scannedCode);
  }
}

Компонент2

@Component({
  selector: 'app-scan-list',
  templateUrl: './scan-list.component.html',
  styleUrls: ['./scan-list.component.css'],
  providers:[CodeServiceService]
})

export class ScanListComponent implements OnInit {

  newcode:Code={
    name:"",
    text:"",
    type:0
  };
constructor(private service:CodeServiceService){
  }
  ngOnInit(){

    this.newcode=this.service.getCode();
console.log(this.newcode);
  }
}

Ответы [ 2 ]

1 голос
/ 14 марта 2019

Это потому что вы используете

 providers:[CodeServiceService]

в обоих компонентах, поэтому создается новый экземпляр службы для обоих компонентов.

использовать providers:[CodeServiceService] в app.module.ts

@NgModule({
   // ..... imports
    providers:[CodeServiceService]
   //..
})

в угловых 6:

Вы можете использовать приведенный ниже код в service.ts вместо добавления в app.module.ts

@Injectable({
  providedIn: 'root',
})
0 голосов
/ 14 марта 2019

Вы можете использовать тему rxjs для этого примера.

1. / Сервис

 import { Observable, Subject } from 'rxjs';
 @Injectable({
    providedIn: 'root'
 })
 export class CodeServiceService {
 codeInfo:Code={
    name:"",
    text:"",
    type:0
 };
 getCode() : Observable<any> {
    return this.subject.asObservable();
}
setCode(result:Code){
   this.subject.next({ text: code });
}

}

2. / component1

 export class NewscanComponent implements OnInit {
 scannedCode:Code={
   name:"name",
   text:"text",
 type:1
 };

 constructor(private service:CodeServiceService){}
 saveInfo(){
   this.service.setCode(this.scannedCode);
 }
}

3. / component2

export class ScanListComponent implements OnInit {
 newcode:Code={
   name:"",
   text:"",
   type:0
};
constructor(private service:CodeServiceService){
}
ngOnInit(){
 this.newcode=this.service.getCode().subscribe(response => {
        console.log(response); // here you can get updated data from another component  
 });
 }
}

Этот метод можно реализовать для отправки данных компоненту, который не имеет отношения родитель-потомок.

...