Я новичок ie и учусь Angular.
Я хочу передавать данные между двумя компонентами (не родительско-дочерний компонент). Я пишу файл service.ts для достижения этой цели, а затем столкнулся с этой ошибкой. Я нашел много в Stackoverflow, но, похоже, никаких эффектов.
Я не знаю, что пошло не так, поэтому выложу весь код.
Ниже приведен код.
Кстати, как решить «Похоже, ваш пост - это в основном код; добавьте еще немного деталей»?
//service
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TransfermessageService {
public receiveMsg:any;
constructor() { }
public subject = new Subject<any>();
sendMessage(message: any) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
//component 1
import { Component, OnInit } from '@angular/core';
import {RequestService} from '../../../services/request/request.service';
import {Router,NavigationStart, GuardsCheckEnd,ResolveStart,NavigationError, Event as NavigationEvent } from '@angular/router';
import {TransfermessageService} from '../../../services/common/transfermessage/transfermessage.service';
@Component({
selector: 'app-login-session-code',
templateUrl: './login-session-code.component.html',
styleUrls: ['./login-session-code.component.scss'],
})
export class LoginSessionCodeComponent implements OnInit {
public riskRole: string = localStorage.getItem('userRole');
public sessioncode: any;
public token_user: any;
constructor(
public RS: RequestService,
public router: Router,
public TMS: TransfermessageService,
) {
}
ngOnInit(){
}
checkInputCall(){
const api = this.RS.baseURL+ '/login/checkInput';
const token_api= this.RS.baseURL+ '/login/checkToken';
const parameters:object = {
"email": localStorage.getItem('email'),
"input": this.sessioncode,
"type": localStorage.getItem('type')
}
this.RS.checkInput(api,parameters).subscribe(res => {
if(res['data'].input_check) {
localStorage.setItem('checkInput', JSON.stringify(res['data']));
this.RS.checkToken(token_api,{"token": res['data'].user.token}).subscribe(res => {
this.token_user = res;
this.TMS.sendMessage({"ss": "ssss"});
this.router.navigate(['/home']);
// console.log(res); //return token_user
})
}else {
alert("session code is not true");
}
})
}
ngAfterViewChecked(): void {
this.router.events.subscribe((event: NavigationEvent) => {
if(event instanceof NavigationStart) {
console.log(event);
}
});
this.router.events.subscribe((event: NavigationEvent) => {
if(event instanceof GuardsCheckEnd) {
console.log(event,'GuardsCheckEnd');
}
});
this.router.events.subscribe((event: NavigationEvent) => {
if(event instanceof NavigationError) {
console.log(event,'NavigationError');
}
});
}
}
//components 2
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {TransfermessageService} from '../../services/common/transfermessage/transfermessage.service';
import {Subscription} from 'rxjs';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
providers: [TransfermessageService]
})
export class HomeComponent implements OnInit {
public ctrlHomeDetailTag: boolean = true;
public ctrlHomeBasicTag: boolean = true;
public ctrlTags: boolean = true;
public receiveMsg: any;
constructor(
public router: Router,
public TMS: TransfermessageService,
public Subscription: Subscription
) {
}
ngOnInit(): void {
console.log('home page');
const receiveMsg = this.TMS.getMessage();
console.log(receiveMsg,'parameters');
}
// ngAfterViewInit():void {
// this.Subscription = this.TMS.getMessage().subscribe(message => {
// this.receiveMsg = JSON.parse(message);
// console.log('this.receiveMsg', this.receiveMsg);
// })
//}
ngonChanges() {
}
ngDoCheck() {
}
ngOnDestroy(): void {
// this.Subscription.unsubscribe();
}
}